I have an enum value as a member of a class which I want to pass as a template argument? The compiler complains that the member can not be used in a constant expression. Is there any magic to get this work?
My current solution is a switch-case statement, but in my original code EType has nearly 200 entries. So my initial idea was to write a type_traits for mapping the enum values to types.
Here is an examples (also on ideone.com) for my problem (the problem is the last line in main()):
#include <iostream>
enum EType
{
eType_A,
eType_B,
eType_C
};
struct Foo
{
Foo(EType eType)
: m_eType(eType)
{
}
EType m_eType;
};
template <EType eType>
struct Bar
{
static std::string const toString()
{
return "-";
}
};
template <>
struct Bar<eType_A>
{
static std::string const toString()
{
return "A";
}
};
template <>
struct Bar<eType_B>
{
static std::string const toString()
{
return "B";
}
};
int main(int argc, char *argv[])
{
std::cout << "Bar<eType_A>::toString()=" << Bar<eType_A>::toString() << "\n";
std::cout << "Bar<eType_B>::toString()=" << Bar<eType_B>::toString() << "\n";
std::cout << "Bar<eType_C>::toString()=" << Bar<eType_C>::toString() << "\n";
Foo stFooA(eType_A);
std::cout << "Bar<stFooA.m_eType>::toString()=" << Bar<stFooA.m_eType>::toString() << "\n"; // <--- here ist the problem
}
The examples generates these errors:
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:54: error: ‘stFooA’ cannot appear in a constant-expression
prog.cpp:54: error: `.' cannot appear in a constant-expression
prog.cpp:54: error: template argument 1 is invalid