Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I switch/select types during compile-time?

Is there a standard way for me to select a type at compile-time on an unsigned index in c++11?

For example, something like:

using type_0 = static_switch<0,T,U>;  // yields type T
using type_1 = static_switch<1,T,U>;  // yields type U

If there is a variadic-template version, it would be very useful.

like image 976
kfmfe04 Avatar asked Mar 14 '13 08:03

kfmfe04


Video Answer


2 Answers

This should work:

template<std::size_t N, typename... T>
using static_switch = typename std::tuple_element<N, std::tuple<T...> >::type;

Another method:

template<std::size_t N, typename T, typename... Ts>
struct static_switch {
  using type = typename static_switch<N - 1, Ts...>::type;
};
template<typename T, typename... Ts>
struct static_switch<0, T, Ts...> {
  using type = T;
};
like image 162
Pubby Avatar answered Oct 22 '22 22:10

Pubby


You could probably use a boost::mpl::vector to store your types and use boost::mpl::at<v,n>::type to get a type with from the index.

template<std::size_t N, typename... T>
using static_switch = typename boost::mpl::at<boost::mpl::vector<T...>, N>::type;
like image 10
Morwenn Avatar answered Oct 22 '22 23:10

Morwenn