Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template for mapping struct type to enum?

I have something like:

struct A { ... };
struct B { ... };
struct C { ... };

class MyEnum {
public:
    enum Value { a, b, c; }
}

template<typename T> MyEnum::Value StructToMyEnum();

template<>
MyEnum::Value StructToMyEnum<A>()
{
   return MyEnum::a;
}

template<>
MyEnum::Value StructToMyEnum<B>()
{
   return MyEnum::b;
}

I basically want to get a directly by calling soemthing like

StructToMyEnum<A>();

This is the best I could come up with, but when I compile I get multiple definition of 'MyEnum::Value StructToMyEnum<A>()' errors when trying to link.

Any recommendations on the best way to map types to enums as per this example?

like image 575
chriskirk Avatar asked Dec 09 '25 01:12

chriskirk


2 Answers

You can map types to enums at compile time:

#include <iostream>

struct A { int n; };
struct B { double f; };
struct C { char c; };

class MyEnum
{
public:
    enum Value { a, b, c };
};

template<typename T> struct StructToMyEnum {};

template<> struct StructToMyEnum<A> {enum {Value = MyEnum::a};};
template<> struct StructToMyEnum<B> {enum {Value = MyEnum::b};};
template<> struct StructToMyEnum<C> {enum {Value = MyEnum::c};};

int main (int argc, char* argv[])
{
    std::cout << "A=" << StructToMyEnum<A>::Value << std::endl;
    return 0;
}
like image 141
jon-hanson Avatar answered Dec 10 '25 15:12

jon-hanson


The multiple definitions are because you need to either add the inline keyword or push the implementation of your specializations into a cpp file, leaving only the declarations of such in the header.

You could probably use mpl::map to write a sort-of generic version. Something like so:

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_<a> >
  , mpl::pair< B, mpl::int_<b> >
  , mpl::pair< C, mpl::int_<c> >
  > type_enum_map;

  typedef typename mpl::at<type_enum_map, T>::type enum_wrap_type;

  return static_cast<Value>(enum_wrap_type::value);
}
like image 37
Edward Strange Avatar answered Dec 10 '25 14:12

Edward Strange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!