c++ - 大括号初始值设定项列表中是否允许显式转换运算符?

标签 c++ c++11 gcc clang compiler-bug

以下代码可以使用 GCC 4.9.2 编译,但不能使用 Clang 3.5.0:

#include <string>

class Foo
{
public:
  explicit operator std::string() const;
};

std::string bar{Foo{}}; // Works in g++, fails in clang++
std::string baz(Foo{}); // Works in both

clang++ 说:

foo.cpp:9:13: error: no matching constructor for initialization of 'std::string'
      (aka 'basic_string<char>')
std::string bar{Foo{}};
            ^  ~~~~~~~
...: note: candidate constructor not viable: no known conversion from 'Foo' to
      'const std::basic_string<char> &' for 1st argument
      basic_string(const basic_string& __str);
      ^

奇怪的是,如果将 std::string 替换为像 int 这样的原始类型,它会起作用。

最佳答案

这似乎是一个 Clang 错误。 [over.match.list]/1:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • [..]
  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

由于第二行编译良好,因此存在不一致:在重载决议方面它们应该是等价的。

关于c++ - 大括号初始值设定项列表中是否允许显式转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27573928/

相关文章:

c++ - “enum class”的递增和递减

performance - BASH:一次设置多个变量/性能

c - 如何从 gcc 限制 C 指令集

c# - 输出图像字符串C++到C#父程序(不保存到硬盘)

c++ - 三角形不出现在OpenGL中?

c++ - 命令提示符中的大输入

c++ - 异构可变参数非类型模板参数计数灵活吗?

c++ - 如何删除 vector 中与另一个 vector 中的某些元素匹配的元素

C - "static"函数的函数原型(prototype)和定义不匹配

c++ - 任何查看 C/CPP 应用程序内存数据结构的方法?