c++ - 如何从 C++ 模板中解压 std::tuple?

标签 c++ templates tuples c++17

我有一门课,预计要参加 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; 
};

现在你可以实例化 MyClasstuple , 像这样:
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/

相关文章:

python - django(但实际上是 python)关于元组的古玩

c++ - 涉及 CRTP 和内部类型的类特化

c++ - 根据条件选择 3 个不同的 map

c++ - 用于 pod 的重载运算符 ==

php - 在哪里为 Woocommerce 添加一个钩子(Hook)函数代码片段?

python - 如何在没有相应值的列表中添加 None ?

python - 优化列表理解以找到互质数对

c++ - Python 和 C++ 中的配置文件过程

c++ - 在 C++ 中是否有任何可移植的方法可以跳转到计算的偏移量?

c++ - gcc 和 class 关键字