Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...