【发布时间】:2017-10-14 02:47:14
【问题描述】:
我有一个类C,它有一个对任何东西的强制转换运算符。在示例中,我尝试以三种不同的方式将其实例转换为std::string:static_cast、std::string 的构造函数和分配给std::string。但是,只有最后一个编译,而其他的则引发了构造函数不明确的错误。
错误的原因很清楚:有很多方法可以将C 转换为std::string 的构造函数可以接受的东西。但是这些案例之间有什么区别呢?为什么 cast 运算符在这里按预期工作,但在那儿不按预期工作?
struct C {
template<typename T>
operator T() const {
return T{};
}
};
int main() {
C c;
cout << static_cast<string>(c) << endl; // compile error
string bad(c); // compile error
string ok = c; // compiles successfully
}
UPD:正如 bolov 在 cmets 中提到的,这个问题不会在 C++17 中重现。我用 g++-5 和 clang-3.8 用 -std=c++11 和 -std=c++14 对其进行了测试,它显示了所描述的错误。
【问题讨论】:
-
无法复制:godbolt.org/g/ESR8cw
-
@bolov 很奇怪,但它不会在 C++17 中重现。它使用 -std=c++11 在 Godbolt 上重现。我会把它添加到帖子中,谢谢。
-
嗯..有趣
-
@bolov 在我这边不能在 gcc/clang 上编译,参见例如here。是的,确实 g++ -std=c++17 接受了代码。
-
@vsoftco 不。如果你也添加
operator const char*,歧义会返回。现在没有模板。
标签: c++ templates casting initialization language-lawyer