简体   繁体   English

用于将struct类型映射到枚举的C ++模板?

[英]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 我基本上是想获得a通过调用soemthing直接像

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. 这是我能想到的最好的,但是当我编译时,我在尝试链接时得到multiple definition of 'MyEnum::Value StructToMyEnum<A>()'错误的multiple definition of 'MyEnum::Value StructToMyEnum<A>()'

Any recommendations on the best way to map types to enums as per this example? 有关根据此示例将类型映射到枚举的最佳方法的任何建议吗?

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

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. 多个定义是因为您需要添加inline关键字或将特化的实现推送到cpp文件中,只在头文件中留下这样的声明。

You could probably use mpl::map to write a sort-of generic version. 你可以使用mpl :: map来编写一个通用版本。 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);
}

Why don't you just make a static member variable of type enum and add it to your structs? 为什么不只是创建一个类型为enum的静态成员变量并将其添加到结构中?

struct A
{
//Stuff

static MyEnum enumType; // Don't forget to assign a value in cpp
};

Than you can just do: 比你可以做的:

MyEnum e = StructA::enumType;

Or do you really want to use templates? 或者你真的想使用模板吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM