c++ - 使用模板类型参数列表中的 TYPE

标签 c++ c++11 templates c++14 variadic-functions

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

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

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 > ();
   }
}

有没有通用的方法...

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

最佳答案

不要重新发明轮子,你可以使用 std::tuplestd::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...
    }
}

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

#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();
}

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

关于c++ - 使用模板类型参数列表中的 TYPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40215134/

相关文章:

c++ - c++ 中的运算符 : how to assign variable value from inside object to int variable using operators in c++

C++从具有相同名称的成员的基类多重继承

javascript - Ember : Log model data in template from a nested route

c++ - 实例化模板时,其不完整参数类型的成员是否应该可见?

c++ - 命名模板参数是在最新标准中还是在现代编译器中实现的?

c++ - 为什么 `this`等于0x0,导致我的程序崩溃?

c++ - 如何在 C++/CX 中创建单例?

c++ - C++模板特化成员函数的定义

c++ - 使用自定义类的指针查找 vector

python - 如何改进 Python C Extensions 文件行读取?