Ho qualcosa come:
struct A { ... }; struct B { ... }; struct C { ... }; class MyEnum { public: enum Value { a, b, c; } } template MyEnum::Value StructToMyEnum(); template MyEnum::Value StructToMyEnum() { return MyEnum::a; } template MyEnum::Value StructToMyEnum() { return MyEnum::b; }
Fondamentalmente voglio ottenere direttamente chiamando tutto come
StructToMyEnum();
Questo è il meglio che potrei multiple definition of 'MyEnum::Value StructToMyEnum()'
, ma quando compilo ottengo multiple definition of 'MyEnum::Value StructToMyEnum()'
quando multiple definition of 'MyEnum::Value StructToMyEnum()'
a collegarmi.
Qualche raccomandazione sul modo migliore per mappare i tipi di enumerazione come in questo esempio?
Le definizioni multiple sono perché è necessario aggiungere la parola chiave inline
o spingere l’implementazione delle specializzazioni in un file cpp, lasciando solo le dichiarazioni di tale nell’intestazione.
Probabilmente potresti usare mpl :: map per scrivere una sorta di versione generica. Qualcosa del genere:
struct A {}; struct B {}; struct C {}; enum Value { a,b,c }; template < typename T > Value get_value() { using namespace boost::mpl; typedef mpl::map < mpl::pair< A, mpl::int_ > , mpl::pair< B, mpl::int_ > , mpl::pair< C, mpl::int_ > > type_enum_map; typedef typename mpl::at::type enum_wrap_type; return static_cast(enum_wrap_type::value); }
Puoi mappare i tipi a enumerazioni in fase di compilazione:
#include struct A { int n; }; struct B { double f; }; struct C { char c; }; class MyEnum { public: enum Value { a, b, c }; }; template struct StructToMyEnum {}; template<> struct StructToMyEnum {enum {Value = MyEnum::a};}; template<> struct StructToMyEnum {enum {Value = MyEnum::b};}; template<> struct StructToMyEnum {enum {Value = MyEnum::c};}; int main (int argc, char* argv[]) { std::cout << "A=" << StructToMyEnum::Value << std::endl; return 0; }
Perché non devi semplicemente creare una variabile membro statica di tipo enum e aggiungerla alle tue strutture?
struct A { //Stuff static MyEnum enumType; // Don't forget to assign a value in cpp };
Di quello che puoi fare:
MyEnum e = StructA::enumType;
O vuoi davvero usare i modelli?