【问题标题】:explicit ctor of unscoped-enum and it's underlying typeunscoped-enum 的显式 ctor 及其底层类型
【发布时间】: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 上表现得很奇怪。

标签: c++ enums


【解决方案1】:

是的,根据 [over.ics.scs],完全匹配优于枚举类型的整数转换。没有隐式转换到枚举类型,任何其他整数(或无范围枚举)类型将选择int重载(与short和long的情况不同,@ 987654324@ 参数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    相关资源
    最近更新 更多