【发布时间】:2021-05-31 15:09:02
【问题描述】:
将一个同时接受无作用域枚举及其基础类型的类声明为显式构造函数是否安全?
enum category : int {
a, b
}
struct foo {
explicit foo(category c) {} // #1
explicit foo(int x) {} // #2
};
foo f1(3); // #2 is called
foo f2(a); // #1 is called
foo f3((a)); // #1 is called
我知道使用作用域枚举是首选,但我只是想知道标准是否保证上述内容是重载的?
【问题讨论】:
-
没有时间找到标准参考,所以我不会发布作为答案,但是是的,这应该是明确定义的。
-
“安全”是什么意思?
-
@Jarod42 我的意思是 enum 类型总是调用
#1而 int 类型总是调用#2。更新了代码中的注释。 -
有点奇怪,但给定
struct S { operator short() const; operator category() const; }; foo f4(S{});,clang++ 和g++ 表示重载不明确,而带有/permissive-的MSVC 使用S::operator category() const和foo::foo(category)进行编译。还不确定哪个是正确的。 -
等等,我现在不确定 MSVC。它目前在 Godbolt 上表现得很奇怪。