如何用不同的枚举定义不同的模板结构
我有两个枚举如下:
enum TTT {t = 2};
enum XXX {x = 2};
我正在尝试建立一些结构来帮助我获得枚举的名字。这是我所做的:
template<TTT>
struct StrMyEnum {
static char const* name() { return "unknown"; }
};
template<>
struct StrMyEnum<t> {
static char const* name() { return "tt"; }
};
它有效。现在,我可以获得Enum t
的名称:strmyenum&lt; t&gt; :: name()
。
但是,如果我为xxx
编写另一组模板结构,则似乎不起作用。
template<XXX>
struct StrMyEnum {
static char const* name() { return "unknown"; }
};
template<>
struct StrMyEnum<x> {
static char const* name() { return "xx"; }
};
现在,我得到了一个编译错误:无法将'x'从'xxx'转换为'ttt'
。似乎编译器正在尝试与strmyenum&lt; x&gt;
与ttt
...
我不知道为什么。
因此,模板无法区分不同的枚举?是否可以为不同的枚举编写一些结构?
I've two enums as below:
enum TTT {t = 2};
enum XXX {x = 2};
I'm trying to make some struct to help me get the name of an enum. Here is what I've done:
template<TTT>
struct StrMyEnum {
static char const* name() { return "unknown"; }
};
template<>
struct StrMyEnum<t> {
static char const* name() { return "tt"; }
};
It works. Now I can get the name of the enum t
: StrMyEnum<t>::name()
.
However, if I write another group of template structs for XXX
, it doesn't seem to work.
template<XXX>
struct StrMyEnum {
static char const* name() { return "unknown"; }
};
template<>
struct StrMyEnum<x> {
static char const* name() { return "xx"; }
};
Now I get a compile error: could not convert 'x' from 'XXX' to 'TTT'
. It seems that the compiler is trying to match the StrMyEnum<x>
with TTT
...
I don't know why.
So template can't distinguish the different enums? Is it possible to write some structs for different enums?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
strmyenum
识别模板的名称。您可以为此提供一般声明,然后是一些专业。
但是,您不能拥有第二组声明 +专业(就像
xxx
的集合一样)。您能做的就是使用一个模板参数化,同时枚举类型和枚举值。
然后,您可以有2个专业级别:
请参阅下面的代码:
输出:
演示: https://godbolt.org/z/z/z/zw547t9nf 。
StrMyEnum
identifies the name of the template.You can have a general declaration for it, and then some specializations.
But you cannot have a second set of declaration + specializations (like you did with the set for
XXX
).What you can do is have one template parametrized with both the enum type and the enum value.
Then you can have 2 levels of specializations:
See the code below:
Output:
Demo: https://godbolt.org/z/zW547T9nf.
您可以使用C ++ 17非类型模板参数,并为
t
和x
做出部分专业化,因为它们实际上是不同的类型demo
You can use C++17 Non-type template parameter and make a partial specialization for
t
andx
, since they are actually different typesDemo