在运行时查询模板专业化的方法/避免大切换
我有一个枚举类型:
enum class MyEnumType { A , B , C };
我想将这些枚举映射到描述属性;我非常喜欢这种方法:
template <typename T>
struct MyEnumTypeDescription
{
inline const char* get() { static_assert("description not implemented for this type"); };
};
template<>
const char* MyEnumTypeDescription<MyEnumType::A>::get() { return "A"; }
template<>
const char* MyEnumTypeDescription<MyEnumType::B>::get() { return "B"; }
....
有点冗长,但也不至于那么糟糕,对吧?
现在,麻烦的部分是当我想在运行时从枚举器获取描述时,这意味着我需要创建一个大开关函数
const char* getDescriptionFromEnumerator( MyEnumType t )
{
case MyEnumType::A:
return MyEnumTypeDescription<MyEnumType::A>::get();
.....
}
是否有一些元编程(模板或宏)魔法可以帮助我避免所有这个样板和容易出错的编码?
I have a enum type:
enum class MyEnumType { A , B , C };
and i want to map these enums to description attributes; i like this approach a lot:
template <typename T>
struct MyEnumTypeDescription
{
inline const char* get() { static_assert("description not implemented for this type"); };
};
template<>
const char* MyEnumTypeDescription<MyEnumType::A>::get() { return "A"; }
template<>
const char* MyEnumTypeDescription<MyEnumType::B>::get() { return "B"; }
....
a bit verbose but not that bad, right?
Now, the part that is cumbersome is when i want to get a description from a enumerator at run-time, it means i need to create a big-switch function
const char* getDescriptionFromEnumerator( MyEnumType t )
{
case MyEnumType::A:
return MyEnumTypeDescription<MyEnumType::A>::get();
.....
}
is there some metaprogramming (template or macro) magic that would help me avoid all this boilerplate and error-prone coding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议将其映射到一个数组:
并且基于索引,您可以在运行时获取类型。
I would suggest to map it to an array:
And based on index you can get the type at runtime.