[英]How to pass an std::map with “any” enum to a function
I have many enum declarations like 我有很多枚举声明,例如
typedef enum {
E_FOO_1,
E_FOO_RANDOM,
E_FOO_25,
} E_FOO;
typedef enum {
E_BAR_RANDOM,
E_BAR_SOMETHING,
E_BAR_WHATEVER,
} E_BAR;
and I need a mapping to strings 我需要一个映射到字符串
std::map<E_FOO, const char*> fooMap = {
{E_FOO_1, "completly different string"},
{E_FOO_RANDOM, "hi"},
{E_FOO_25, "down"},
};
std::map<E_BAR, const char*> barMap = {
{E_BAR_RANDOM, "1234"},
{E_BAR_SOMETHING, "3},
{E_BAR_WHATEVER, "45"},
};
Is there anyway to write a function which takes something like (uint8_t someEnumValue, std::map<any, const char*>)
and simply returns the string? 无论如何,有没有写一个函数来接受类似(uint8_t someEnumValue, std::map<any, const char*>)
并简单地返回字符串?
In the real application the structure is much more complicated and the enums
are handled by some C-code, which has no problem to handle the enum values as int
or uint8_t
but I am not very used to C++, so I see no way to pass these parameters to a general function. 在实际应用中,结构要复杂得多,并且enums
由某些C代码处理,这对于将枚举值作为int
或uint8_t
进行处理没有问题,但是我不太习惯C ++,所以我看不到任何传递方法这些参数成为一般功能。
Could it be done by using templates? 可以通过使用模板来完成吗? And wouldn't that blow up the compiled code since for every enum
the function needs to be compiled (the function would be in a bigger class, so I would need to template the whole class). 而且这不会破坏已编译的代码,因为对于每个enum
,都需要编译函数(该函数将在更大的类中,因此我需要对整个类进行模板化)。
Thanks! 谢谢!
You can use a function template to accept any std::map
whose value type is const char*
: 您可以使用函数模板接受任何类型为const char*
std::map
:
template <typename Enum>
const char* get_string(std::uint8_t v, const std::map<Enum, const char*>& m)
{
return m.at(static_cast<Enum>(v));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.