c++ 转换类型元编程

sczxawaw  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(266)

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

  1. #include <iostream>
  2. template<typename... Ts>
  3. struct Typelist {};
  4. template <typename List>
  5. struct front{};
  6. template<typename Head, typename... Tail>
  7. struct front<Typelist<Head, Tail...>>
  8. {
  9. using type = Typelist<std::array<Head, 10>, front<Typelist<Tail...>>>;
  10. };
  11. void seetype(auto) {std::cout << __PRETTY_FUNCTION__ << std::endl;}
  12. int main()
  13. {
  14. using list_of_types = Typelist<long, float, char>;
  15. using arrays_of_types = front<list_of_types>::type;
  16. seetype(arrays_of_types{});
  17. return 0;
  18. }

字符串
结果是这样

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


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

cgh8pdjw

cgh8pdjw1#

你的代码有几个问题:

  1. front<Typelist<Tail...>>

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

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


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

  1. template<typename Head>
  2. struct front<Typelist<Head>>
  3. {
  4. using type = Typelist<std::array<Head, 10>>;
  5. };


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

  1. template<typename List1, typename List2>
  2. struct concat {};
  3. template<typename... Ts, typename...Us>
  4. struct concat<Typelist<Ts...>, Typelist<Us...>> {
  5. using type = Typelist<Ts..., Us...>;
  6. };


  1. template<typename Head, typename... Tail>
  2. struct front<Typelist<Head, Tail...>>
  3. {
  4. using type = typename concat<Typelist<std::array<Head, 10>>,
  5. typename front<Typelist<Tail...>>::type>::type;
  6. };


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

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


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

  1. template <template <typename> class F, typename List>
  2. struct Mapping{
  3. };
  4. template<template <typename> class F, typename... Ts>
  5. struct Mapping<F, Typelist<Ts...>>
  6. {
  7. using type = Typelist<typename F<Ts>::type...>;
  8. };
  9. template<typename T>
  10. struct to_array_10
  11. {
  12. using type = std::array<T, 10>;
  13. };
  14. using list_of_types = Typelist<long, float, char>;
  15. using arrays_of_types = Mapping<to_array_10, list_of_types>::type;


Demo

展开查看全部

相关问题