首页 > 解决方案 > 来自枚举值的 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 == )编程风格?

标签: c++templates

解决方案


我想要的东西就像 [...] 的道德等价物完全可能是这样的 - 而不诉诸 if (enum_value == ) 编程风格?

如果您enum_value作为参数(运行时已知)传递给make_array().

C++ 是静态类型语言,所以编译器必须在编译时决定函数的返回类型,所以编译器必须知道编译时的enum_value.

要解决这个问题,可以传递enum_valueas 模板参数。

关于枚举/类型转换,在我看来,您需要以下内容

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 {}; }

推荐阅读