c++ - 来自枚举值的 C++ decltype
问题描述
我有一个现有的代码库,它使用旧式枚举来标记类型:
enum value_type {
FLOAT = 1,
DOUBLE = 2,
INT = 3
};
然后我想std::vector<T>
基于枚举值进行实例化 - 即:
auto make_vector( value_type enum_value ) -> decltype(std::vector<decltype( enum_value )>) {
...
}
当然,decltype(enum_value)
这不起作用 - 我想要的东西类似于道德上的等价物:
if (enum_value == FLOAT)
return decltype(double());
if (enum_value == DOUBLE)
return decltype(float());
...
这样的事情是否可能 - 不诉诸if (enum_value == )
编程风格?
解决方案
我想要的东西就像 [...] 的道德等价物完全可能是这样的 - 而不诉诸 if (enum_value == ) 编程风格?
如果您enum_value
作为参数(运行时已知)传递给make_array()
.
C++ 是静态类型语言,所以编译器必须在编译时决定函数的返回类型,所以编译器必须知道编译时的enum_value
.
要解决这个问题,可以传递enum_value
as 模板参数。
关于枚举/类型转换,在我看来,您需要以下内容
template <value_type>
struct getType;
template <> struct getType<FLOAT> { using type = float; };
template <> struct getType<DOUBLE> { using type = double; };
template <> struct getType<INT> { using type = int; };
现在可以编写make_vector()
如下函数
template <value_type enum_value>
auto make_vector ()
-> std::vector<typename getType<enum_value>::type>
{ return {}; }
推荐阅读
- flutter - 使用 bottomSheet 时脚手架主体不可见
- forms - VueJs 温度验证
- spring - 存储库未启动
- javascript - 带有使用 es6 模块的外部库的打字稿
- sql - 合并两个 SQL 查询以在单个表中获取输出
- javascript - 如何获取参数函数javascript
- lua - 在 Windows 10 上设置 luarocks
- google-sheets-api - google.Script.run 未返回有关 DOMContentLoaded 执行的数据
- pytorch - 带有pytorch的resnet50中缺少/意外的键
- excel - 检查单元格的百分比格式