【问题标题】:How do I replace a tuple element at compile time?如何在编译时替换元组元素?
【发布时间】:2013-03-02 21:43:40
【问题描述】:

有没有办法在编译时替换元组元素?

例如,

using a_t = std::tuple<std::string,unsigned>;  // start with some n-tuple
using b_t = element_replace<a_t,1,double>;     // std::tuple<std::string,double>
using c_t = element_replace<b_t,0,char>;       // std::tuple<char,double>

【问题讨论】:

    标签: c++ templates stl c++11


    【解决方案1】:

    【讨论】:

    • 虽然是个好建议……但它也严重缺乏肉类。仅链接的答案不受欢迎,请不要发布此类。
    【解决方案2】:

    您可以使用std::tuple_element 访问元组类型的元素的类型。这实际上不允许您替换元组元素类型,但它允许您根据在其他元组类型中用作元素类型的类型来定义元组类型。

    【讨论】:

      【解决方案3】:

      你可以用这个:

      // the usual helpers (BTW: I wish these would be standardized!!)
      template< std::size_t... Ns >
      struct indices
      {
          typedef indices< Ns..., sizeof...( Ns ) > next;
      };
      
      template< std::size_t N >
      struct make_indices
      {
          typedef typename make_indices< N - 1 >::type::next type;
      };
      
      template<>
      struct make_indices< 0 >
      {
          typedef indices<> type;
      };
      
      // and now we use them
      template< typename Tuple, std::size_t N, typename T,
                typename Indices = typename make_indices< std::tuple_size< Tuple >::value >::type >
      struct element_replace;
      
      template< typename... Ts, std::size_t N, typename T, std::size_t... Ns >
      struct element_replace< std::tuple< Ts... >, N, T, indices< Ns... > >
      {
          typedef std::tuple< typename std::conditional< Ns == N, T, Ts >::type... > type;
      };
      

      然后像这样使用它:

      using a_t = std::tuple<std::string,unsigned>;     // start with some n-tuple
      using b_t = element_replace<a_t,1,double>::type;  // std::tuple<std::string,double>
      using c_t = element_replace<b_t,0,char>::type;    // std::tuple<char,double>
      

      【讨论】:

      • +1 - 只是一个小修正:我认为你需要 Tuple in std::tuple_size&lt;Tuple&gt;
      • @kfmfe04:天啊!当然,在我的测试代码中有它并且忘记了编辑。现已修复!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      相关资源
      最近更新 更多