c++ - 从元组派生类

标签 c++ templates c++11 variadic-templates template-templates

我有一个这样的 std::tuple:

typedef std::tuple<t1, t2, t3> tuple_t;

现在,我想将 t3_tuple 转换成类似的元组:

typedef std::tuple< T<t1>, T<t2>, T<t3> > derived_tuple_t;

例如,在我的例子中,t1t2t3 是原语,T标准::堆栈。一般来说,假设可能有 t4 等等。

当然,我的第二个定义已经解决了这个问题,但我希望推导是自动的:只给定 Ttuple_t,构建我 derived_tuple_t。像这样:

template <class T, class tuple_t> using derived_tuple_t = std::tuple</*???*/>;

这样的事情可能吗?也许是一个简短的解决方案?

最佳答案

您可以使用两个模板参数声明结构 update_tuple:

  1. T - 将被模板化,我们将把这个参数应用到 tuple
  2. 中的参数
  3. std::tuple 具有可变数量的模板参数。

然后只需为新的 tuple 创建一个别名,并使用包扩展将参数应用于 T

#include <tuple>
#include <type_traits>
#include <vector>

template <template<class...> class, class>
struct update_tuple;

template <template <class...> class T, class... Args>
struct update_tuple<T, std::tuple<Args...>>
{
    using type = std::tuple<T<Args>...>;
};

int main()
{
    static_assert
    (
        std::is_same
        <
            std::tuple<std::vector<int>, std::vector<double>>,
            update_tuple<std::vector, std::tuple<int, double>>::type
        >::value,
        "They are not same"
    );
    return 0;
}

感谢@Xeo:如果 T 可以接受多个模板参数(当其他但第一个具有默认值时),代码将不会失败。

Example

关于c++ - 从元组派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17103860/

相关文章:

c++ - C++ 中 char* 中的子字符串,strtok 到行尾

C++,如何找到成员函数的地址?

c++ - 服务器应用程序框架(最好使用 BOOST C++)

c++ - 将模板化基类转换运算符引入派生范围

c++ - 类内模板化类的 Typedef

C++11 和 Visual Studio - 未解析的外部符号

javascript - 使用 Smarty 模板的动态页面布局

c++ - 为什么 std::min(std::initializer_list<T>) 按值获取参数?

当 base 不在 [2,36] (GCC) 中时,C++11 std::stoi 静默失败

c++ - 为什么是 lambda 而不是局部函数?