使用tempate类型参数列表中的TYPE

rnd*_*gen 6 c++ templates variadic-functions c++11 c++14

我想使用类模板参数列表中的类型信息.

快速解决方法的工作示例:

struct NoParam {};
template< typename A = NoParam,
          typename B = NoParam,
          typename C = NoParam,
          typename D = NoParam,
          typename E = NoParam,
          typename F = NoParam >
struct TypeList
{
  typedef A T1;
  typedef B T2;
  typedef C T3;
  typedef D T4;
  typedef E T5;
  typedef F T6;
};

template<typename... Types>
class Application
{
   Application()
   {
      // the actual code will store the created instances in a tuple or map..
      std::make_unique< TypeList<Types...>::T1 > ();
      std::make_unique< TypeList<Types...>::T2 > ();
      std::make_unique< TypeList<Types...>::T3 > ();
      std::make_unique< TypeList<Types...>::T4 > ();
      std::make_unique< TypeList<Types...>::T5 > ();
      std::make_unique< TypeList<Types...>::T6 > ();
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有通用的方法......

  • 迭代类型并获取类型信息(用于创建实例)
  • 在示例中仅限于6种类型的硬编码

sky*_*ack 4

不要重新发明轮子,你可以使用std::tupleandstd::tuple_element_t为此:

template<typename... T>
using TypeList = std::tuple<T...>;

template<int I, typename T>
using Type = std::tuple_element_t<I, T>;

template<typename... Types>
class Application {
    Application() {
        std::make_unique<Type<0, TypeList<Types...>>> ();
        std::make_unique<Type<1, TypeList<Types...>>> ();
        // and so on...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在迭代类型非常简单。
它遵循一个最小的工作示例来向您展示如何做到这一点:

#include <tuple>
#include <functional>
#include <memory>

template<typename... T>
using TypeList = std::tuple<T...>;

template<int I, typename T>
using Type = std::tuple_element_t<I, T>;

template<typename... Types>
class Application {
    using MyTypeList = TypeList<Types...>;

    template<std::size_t... I>
    void iterate(std::index_sequence<I...>) {
        // demonstration purposes, here I'm simply creating an object of the i-th type
        int _[] = { 0, (Type<I, MyTypeList>{}, 0)... };
        (void)_;
    }

public:
    void iterate() {
        iterate(std::make_index_sequence<sizeof...(Types)>{});
    }

    Application() {
        std::make_unique<Type<0, MyTypeList>> ();
        std::make_unique<Type<1, MyTypeList>> ();
        // and so on...  
    }
};

int main() {  
    Application<int, float> app;
    app.iterate();
}
Run Code Online (Sandbox Code Playgroud)

请注意,std::index_sequencestd::make_index_sequence自 C++14 起可用。不管怎样,如果您受限于 C++11,您可以在线找到几种可以使用的实现。
否则,您还可以使用几个递归 _sfinae'd_functions 来迭代类型,以检查是否sizeof...(Types)已达到。