I have an existing code base which uses an old style enum to label a type:
enum value_type {
FLOAT = 1,
DOUBLE = 2,
INT = 3
};
I would then like to instantiate std::vector<T>based on the enum value - i.e. something like:
auto make_vector( value_type enum_value ) -> decltype(std::vector<decltype( enum_value )>) {
...
}
Of course the decltype(enum_value) does not work - what I would want something like the moral equivalent of:
if (enum_value == FLOAT)
return decltype(double());
if (enum_value == DOUBLE)
return decltype(float());
...
is something like this at all possible - without resorting to the if (enum_value == ) style of programming?
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; };
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 {}; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With