首页 > 解决方案 > 是否有适当的方法来根据编译时传递的模板值参数来别名类型(c ++)

问题描述

我想根据传递的模板参数来别名类型。根据传递的模板参数 int 值,确定返回类型。但我想要的有很多类型。我想用干净的代码做到这一点。

我知道我可以用 来做到这一点std::conditional_t,但它真的很乱。我需要从 int 值中为许多类型起别名

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

}

但我想要更干净的方式。实际上,如果我只是将类型放在返回类型上,我可以这样做,但我想使用模板值参数。

我不知道我应该为此使用什么。

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

   case 2:
   using type = typename Type2
   break;

}

我知道这段代码格式不正确,但这个概念正是我想要的。

标签: c++c++17

解决方案


不,我看不到获得用于声明using类型的 switch 语句的方法。

我能想象的最好的通过结构模板专业化

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

推荐阅读