c – 如何在编译时替换元组元素?

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

例如,

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,char>;       // std::tuple<char,double>

解决方法

你可以使用这个:
// 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... Ns >
struct element_replace< std::tuple< Ts... >,N,T,indices< Ns... > >
{
    typedef std::tuple< typename std::conditional< Ns == N,Ts >::type... > type;
};

然后使用它:

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...