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

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

c++17 - 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.

question from:https://stackoverflow.com/questions/65644740/is-there-proper-way-to-alias-type-depending-on-passed-template-value-argument-at

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

1 Answer

0 votes
by (71.8m points)

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 ()
 {
   // ...
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...