user422005
user422005

Reputation: 2031

C++ decltype from enum value

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?

Upvotes: 3

Views: 1561

Answers (2)

max66
max66

Reputation: 66190

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

Upvotes: 6

bartop
bartop

Reputation: 10315

If you don't necessarily need enum and can use tag types you can use tag dispatch overloading:

struct float_type_tag {} FLOAT;
struct int_type_tag {} INT;

std::vector<int> make_vector(int_type_tag);
std::vector<float> make_vector(float_type_tag );

Upvotes: 1

Related Questions