是否可以将两个模板类传递给一个模板类?
我希望创建一个包含两个不同 std::tuple<std::vector<>>
的类.
我开始怀疑我想要实现的目标无法完成,但我找不到任何相反的说法。
下面是我正在使用的代码:
#include <iostream>
#include <vector>
#include <tuple>
template<typename... Ts>
struct Typelist
{
static constexpr std::size_t size { sizeof...(Ts) };
};
template<class, class> class World;
template<template<typename... Arg1> class T1, template<typename... Arg2> class T2>
class World<Typelist, Typelist>
{
private:
std::tuple<std::vector<T1>...> m1;
std::tuple<std::vector<T2>...> m2;
};
int main() {
// your code goes here
using TL1 = Typelist<int, char, double>;
using TL2 = Typelist<float, unsigned int, bool>;
World<TL1, TL2> w2;
return 0;
}
这可能吗?如果可能,我做错了什么? 如果没有,是否有可能的替代方案?
最佳答案
这就是我想你可能的意思。
#include <iostream>
#include <vector>
#include <tuple>
template<typename... Ts>
struct Typelist
{
static constexpr std::size_t size { sizeof...(Ts) };
};
template <class, class>
class World;
template <typename... Arg1, typename... Arg2>
class World<Typelist<Arg1...>, Typelist<Arg2...>>
{
private:
std::tuple<std::vector<Arg1>...> m1;
std::tuple<std::vector<Arg2>...> m2;
};
int main() {
using TL1 = Typelist<int, char, double>;
using TL2 = Typelist<float, unsigned int, bool>;
World<TL1, TL2> w2;
return 0;
}
所做的更改:
首先,模板特化改为两个裸参数包,这是可行的,因为参数包是由模板匹配引擎根据Typelist
的类型填充的,所以是明确的.您不能使用您之前使用的规范,因为那样您只能访问 T1
和 T2
,您无权访问内部参数包参数的名称。
其次,我更改了 World
的数据成员的定义方式,因此 m1
和 m2
是类型 vector 的元组。
第三,你可以完全摆脱Typelist
,直接使用tuple
。除非它正在执行此代码中未包含的内容。
#include <iostream>
#include <vector>
#include <tuple>
template <class, class>
class World;
template <typename... Arg1, typename... Arg2>
class World<std::tuple<Arg1...>, std::tuple<Arg2...>>
{
private:
std::tuple<std::vector<Arg1>...> m1;
std::tuple<std::vector<Arg2>...> m2;
};
int main() {
using TL1 = std::tuple<int, char, double>;
using TL2 = std::tuple<float, unsigned int, bool>;
World<TL1, TL2> w2;
return 0;
}
关于c++ - 模板类的多个模板模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293532/