我有一个使用旧式枚举来标记类型的现有代码库:
enum value_type {
FLOAT = 1,
DOUBLE = 2,
INT = 3
};
Run Code Online (Sandbox Code Playgroud)
然后,我想std::vector<T>基于枚举值实例化-即类似:
auto make_vector( value_type enum_value ) -> decltype(std::vector<decltype( enum_value )>) {
...
}
Run Code Online (Sandbox Code Playgroud)
当然,这decltype(enum_value)是行不通的-我想要像道德上这样的东西:
if (enum_value == FLOAT)
return decltype(double());
if (enum_value == DOUBLE)
return decltype(float());
...
Run Code Online (Sandbox Code Playgroud)
这样完全有可能-不用求助于if (enum_value == )编程风格吗?
what I would want something like the moral equivalent of [...] is something like this at all possible - without resorting to the if (enum_value == ) style of programming?
It's not possible if you pass enum_value as argument (run-time known) to make_array().
C++ is a static typed language, so the compiler must decide compile-time the return type of the function, so the compiler must known compile-time the enum_value.
To solve this problem, you can pass the enum_value as template parameter.
About the enum/type conversion, it seems to me that you need something as follows
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; };
Run Code Online (Sandbox Code Playgroud)
Now you can write a make_vector() function as follows
template <value_type enum_value>
auto make_vector ()
-> std::vector<typename getType<enum_value>::type>
{ return {}; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |