SungJinKang
SungJinKang

Reputation: 429

Is there proper way to alias type depending on passed template value argument at compile time (c++)

I wanna alias type according to passed template argument. Depending on Passed Template argument int value, return Type is decided. but there is many types what I want. I wanna do this with clean code.

I know I can do this with std::conditional_t, but it's really messy. I need aliasing many types from int value

template <int value>
std::conditional_t<value== 1, Type1, std::conditional_t<value== 2, Type2, std::conditional_t<value== 3, Type3, Type4>>> Function()
{

}

but I wanna more clean ways. Actually if I just put type at return type, I can do this, but I wanna use template value argument.

I don't know what should I use for this.

switch(value)
{
   case 1:
   using type = typename Type1;
   break;

   case 2:
   using type = typename Type2
   break;

}

I know this code is ill-formed, but this concept is what I want.

Upvotes: 1

Views: 86

Answers (2)

JHBonarius
JHBonarius

Reputation: 11281

You can use a tuple:

#include <tuple>

template <std::size_t N>
using FunctionRetType = std::tuple_element_t<N, std::tuple<
    /*0*/int,
    /*1*/bool,
    /*2*/float>>;

Applied:

template <std::size_t N>
constexpr FunctionRetType<N> Function() { return 0; }

#include <type_traits>

int main()
{
    static_assert(std::is_same_v<decltype(Function<1>()), bool>);
}

And you can always add arithmetic on the N argument, for instance to realize 1-based indexing.

Upvotes: 2

max66
max66

Reputation: 66230

No, I don't see a way to get a switch statement for declaring a using type.

The best I can imagine pass through a struct template specialization

template <int>
struct my_type;

template <> struct my_type<1> { using type = Type1; };
template <> struct my_type<2> { using type = Type2; };
template <> struct my_type<3> { using type = Type3; };

template <int value>
using my_type_t = typename my_type<value>::type;

template <int value>
my_type_t<value> Function ()
 {
   // ...
 }

Upvotes: 3

Related Questions