c++ 转换类型元编程

sczxawaw  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(188)

我是新手,我不知道元编程,我正在尝试转换这样的列表
Typelist<std::array<long, 10>, std::array<float, 10>, std::array<char, 10>>中的Typelist<long, float, char>

#include <iostream>

template<typename... Ts>
struct Typelist {};

template <typename List>
struct front{};

template<typename Head, typename... Tail>
struct front<Typelist<Head, Tail...>>
{
    using type = Typelist<std::array<Head, 10>, front<Typelist<Tail...>>>;
};

void seetype(auto) {std::cout << __PRETTY_FUNCTION__ << std::endl;}

int main()
{
    using list_of_types = Typelist<long, float, char>;
    using arrays_of_types = front<list_of_types>::type;
    seetype(arrays_of_types{});
    return 0;
}

字符串
结果是这样

void seetype(auto) [auto:1 = Typelist<std::array<long, 10>, front<Typelist<float, char>>>]


只有第一种是好的,休息不好......什么是错的

cgh8pdjw

cgh8pdjw1#

你的代码有几个问题:

front<Typelist<Tail...>>

字符串
不是修改的类型,则需要

typename front<Typelist<Tail...>>::type


(这是一个Typelist)那么递归的基本情况不被处理:

template<typename Head>
struct front<Typelist<Head>>
{
    using type = Typelist<std::array<Head, 10>>;
};


这样,得到的类型没有正确地连接Demo,所以:

template<typename List1, typename List2>
struct concat {};

template<typename... Ts, typename...Us>
struct concat<Typelist<Ts...>, Typelist<Us...>> {
    using type = Typelist<Ts..., Us...>;
};


template<typename Head, typename... Tail>
struct front<Typelist<Head, Tail...>>
{
    using type = typename concat<Typelist<std::array<Head, 10>>,
                                 typename front<Typelist<Tail...>>::type>::type;
};


Demo
但是你根本不需要递归:

template<typename... Ts>
struct front<Typelist<Ts...>>
{
    using type = Typelist<std::array<Ts, 10>...>;
};


就足够了:
Demo
更一般的是:

template <template <typename> class F, typename List>
struct Mapping{
};

template<template <typename> class F, typename... Ts>
struct Mapping<F, Typelist<Ts...>>
{
    using type = Typelist<typename F<Ts>::type...>;
};

template<typename T>
struct to_array_10
{
    using type = std::array<T, 10>;
};

using list_of_types = Typelist<long, float, char>;
using arrays_of_types = Mapping<to_array_10, list_of_types>::type;


Demo

相关问题