user2746401 user2746401 - 4 months ago 13
C++ Question

Type based on template argument value

I currently have a template function something like this:

enum class MyEnum { ENUM_1, ENUM_2, ENUM_3 };

template<MyEnum e, typename T>
void func( int i )
{
std::vector<T> someData = ......;
T someValue;

switch( e )
{
case ENUM_1:
someValue += func1( someData );
break;
case ENUM_2:
someValue += func2( someData );
break;
case ENUM_3:
someValue += func3( someData );
break;
}
}


The type
T
is dependent on the value of
e
. I'd like to write this code like

template<MyEnum e>
void func( int i )
{
if( e = MyEnum:ENUM_1 ) T = char;
else T = float;

std::vector<T> someData = ......;
T someValue;

switch( e )
{
case ENUM_1:
someValue += func1( someData, ..... );
break;
case ENUM_2:
someValue += func2( someData, ..... );
break;
case ENUM_3:
someValue += func3( someData, ..... );
break;
}
}


I can see how to make a type dependent on another type, e.g.

typedef std::conditional<std::is_same<T1, float>::value, char, float>::type T;


but can't figure out how to extend this to cope with enum values. Is it possible to do what I want to? If so, how?

Note:
func1
,
func2
and
func3
are fixed and beyond my control.

Thanks!

Answer

The first template parameter for std::conditional is just a plain old bool, so you can just shove your logic in there:

using T = typename std::conditional<(e == MyEnum::ENUM_1), char, float>::type;
using T = std::conditional_t<(e == MyEnum::ENUM_1), char, float>; //C++14