c++ - 替换可变参数模板列表中的第 n 个元素

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

我尝试使用 THIS ANSWER获得以下工作: (替换可变列表中的第 n 个元素并将其打包为元组)

template<typename... Ts>
using pack_as_tuple = std::tuple<Ts...>;


template< std::size_t N, typename T, typename... Ts>
struct replace_nth_type_in_list
{
    typedef replace_nth_type<N,T, pack_as_tuple<Ts...>> type;
};


int main()
{
    using U = std::tuple<std::string,unsigned,size_t,double>;
    using rep0 = replace_nth_type<0,char,U>::type;
    using rep1 = replace_nth_type<1,char,U>::type;
    using rep2 = replace_nth_type<2,char,U>::type;
    using rep3 = replace_nth_type<3,char,U>::type;
    static_assert(std::is_same<rep0, std::tuple<char,unsigned,size_t,double>>::value, "Error!");
    static_assert(std::is_same<rep1, std::tuple<std::string, char,size_t,double>>::value, "Error!");
    static_assert(std::is_same<rep2, std::tuple<std::string, unsigned,char,double>>::value, "Error!");
    static_assert(std::is_same<rep3, std::tuple<std::string, unsigned,size_t,char>>::value, "Error!");

    using repList0 = replace_nth_type_in_list<0,char,std::string,unsigned,size_t,double>::type;
    static_assert(std::is_same<repList0, std::tuple<char,unsigned,size_t,double>>::value, "Error!");
    return 0;
}

但是触发了最后一个静态断言。您可以查看现场示例 HERE 有人可以向我解释为什么会发生这种情况以及如何解决这个问题吗?

最佳答案

明白了!就是这一行:

typedef replace_nth_type<N,T, pack_as_tuple<Ts...>> type;

它应该是:

typedef typename replace_nth_type<N,T, pack_as_tuple<Ts...>>::type type;

否则你的 type将是 replace_nth_type<...> 类型而不是它应该创建的类型,它作为 typedef “返回”也称为 type replace_nth_type .因此你想要 typename replace_nth_type<...>::type得到std::tuple<...>它创造了。

关于c++ - 替换可变参数模板列表中的第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460637/

相关文章:

C++:int64_t 它来自哪里?

c++ - 将 QMap 转换为 JSON

c++ - 是否可以在 qmake .pro 文件中设置 visual studio 项目属性?

c++ - 在 C++ 中使用指针会减少运行时间?

c++ - 在容器条目上放置互斥锁的安全有效的方法

c++ - 无参数可变参数模板的模糊重载

c++ - 将 std::function 与 lambda 和可变参数模板一起使用

android ndk 和 eclipse 给出了关于 c++ getline() 函数的不同错误信息

c++ - 相机校准和坐标转换(OpenCV)

c++ - 如何编写具有不同数量的信息参数的 C++ 断言宏?