c++ - 是否有适当的方法来根据编译时传递的模板值参数来别名类型(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;
}
我知道这段代码格式不正确,但这个概念正是我想要的。
解决方案
不,我看不到获得用于声明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 ()
{
// ...
}
推荐阅读
- wordpress - 带有 Timber/Twigg 模板的 WordPress 前端的 TinyMCE
- sql-server - 选择具有不同列值的不同 ID
- python - python的问题:未定义的符号:sqmI
- qemu - U-Boot with OpenSBI on HiFive Unleashed in QEMU: Store/AMO access fault
- javascript - 在 React 应用程序的 Util 文件中初始化 Google 地图
- android-studio - 为什么我没有收到错误并且应用程序无法打开
- sql - 将字符串类型的日期和时间连接到一个 TIMESTAMP 列 [Impala]
- variables - 在 TFS 2018 Release Task 之间传递一个变量,然后在门步骤中使用该变量
- node.js - req.body 始终是一个空对象
- python - 一旦在python中打开一个变量分配给一个文件,当重新分配变量时文件会发生什么?