我想使用类模板参数列表中的类型信息。
快速解决方法的工作示例:
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::tuple
和 std::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_sequence
和 std::make_index_sequence
自 C++14 起可用。不管怎样,如果你受限于 C++11,你可以在网上找到几个要使用的实现。
否则,您还可以使用几个递归 _sfinae'd_functions 来迭代类型,这些函数检查是否已达到 sizeof...(Types)
。
关于c++ - 使用模板类型参数列表中的 TYPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40215134/