【问题标题】:replacing the n-th element from a variadic template list替换可变参数模板列表中的第 n 个元素
【发布时间】:2013-03-17 12:21:04
【问题描述】:

我尝试使用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 有人可以向我解释一下,为什么会发生这种情况以及如何解决这个问题?

【问题讨论】:

  • 现场示例的链接对我来说已损坏。你如何定义replace_nth_type
  • 函数在我链接的答案中定义 - 这个更好吗:liveworkspace.org/code/2Qqz2V$0

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


【解决方案1】:

知道了!就是这一行:

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&lt;...&gt; 类型,而不是它应该创建的类型,并且它作为 typedef “返回”,也称为 type within em>replace_nth_type。因此,您希望 typename replace_nth_type&lt;...&gt;::type 获得它创建的 std::tuple&lt;...&gt;

【讨论】:

  • 我猜还是有问题。 Here 最后一个断言应该触发,但它没有......或者我错过了什么?
  • 是的,这解决了它,但是为什么没有额外的 typename 和 ::type 就可以编译?
  • @DanielFrey:正确,我只是感到困惑。对此感到抱歉
  • @user2081073:因为您将 replace_nth_type&lt;...&gt; 本身作为类型,请参阅我的编辑。
猜你喜欢
  • 2020-01-10
  • 2013-12-08
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多