以下代码可以使用 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/