replacing the n-th element from a variadic template list

ε祈祈猫儿з 提交于 2019-12-12 04:25:01

问题


I tried to use THIS ANSWER to get the following working: (replacing the n-th element from a variadic list and packing it as a tuple)

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;
}

But the last static assert is triggered. You can see the live example HERE Can somebody explain to me, why this happens and how to solve this?


回答1:


Got it! It's this line:

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

it should read:

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

because otherwise your type will be of type replace_nth_type<...> and not the type that it is supposed to create and which is "returned" as a typedef that is also called type within replace_nth_type. Hence you want the typename replace_nth_type<...>::type to get the std::tuple<...> it created.



来源:https://stackoverflow.com/questions/15460637/replacing-the-n-th-element-from-a-variadic-template-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!