Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to replace a tuple element at compile time?

For example,

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use this:

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

and then use it like this:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...