我有一门课,预计要参加 std::tuple
某些类型(允许任意计数)作为模板参数。我想声明一个类型 vector 的元组。例如,我有
template <typename T>
class MyClass {/*...*/}
我实例化它
MyClass<std::tuple<int, bool>> my_class;
我的目标是创造一个这样的领域
std::tuple<std::vector<int>, std::vector<bool>> my_tuple;
我知道如果我有一个类定义
template <typename... T>
class MyClass2 {/*...*/}
我可以通过传递没有元组的数据类型来实例化它
MyClass<int, bool> my_class2;
然后简单地创建字段
std::tuple<std::vector<int>, std::vector<bool>> my_tuple2;
使用
std::tuple<std::vector<T>...> my_tuple2;
因此,我想我应该以某种方式从元组中解压缩数据类型。是否可以?
最佳答案
当然,您只需要另一个间接级别(像往常一样):
// this function declaration is used just for the type
// transformation, and needs no definition
template <typename... Types>
auto unpack(std::tuple<Types...>) -> std::tuple<std::vector<Types>...> ;
template <typename Tuple>
class MyClass
{
// use the return type of unpack
decltype(unpack(std::declval<Tuple>())) my_tuple;
};
现在你可以实例化
MyClass
与 tuple
, 像这样:MyClass<std::tuple<int, double>> m;
其中包含一个字段
my_tuple
类型std::tuple<std::vector<int>, std::vector<double>>
这是一个工作demo .
关于c++ - 如何从 C++ 模板中解压 std::tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61261629/