【发布时间】:2019-02-08 11:32:36
【问题描述】:
以下代码在 gcc 7.3.0 中编译良好,但不能在 clang 6.0.0 中编译。
#include <string>
struct X {
X() : x(10) {}
int operator[](std::string str) { return x + str[0]; }
template <typename T> operator T() { return x; } // (1) fails only in clang
//operator int() { return x; } // (2) fails both in gcc and clang
private:
int x;
};
int main() {
X x;
int y = 20;
int z = int(x);
return x["abc"];
}
我使用命令clang++ 1.cpp -std=c++98 指定不同的标准版本。我试过 c++98,11,14,17,2a。在所有情况下,错误都是相同的。 clang 中的错误信息如下:
1.cpp:14:13: error: use of overloaded operator '[]' is ambiguous (with operand types 'X' and 'const char [4]')
return x["abc"];
~^~~~~~
1.cpp:5:9: note: candidate function
int operator[](std::string str) { return x + str[0]; }
^
1.cpp:14:13: note: built-in candidate operator[](long, const char *)
return x["abc"];
^
1.cpp:14:13: note: built-in candidate operator[](long, const volatile char *)
1 error generated.
什么编译器在这种情况下正确地遵循标准?它是有效的代码吗?
问题描述可以在here找到,不过是关于情况(2)。我对案例(1)感兴趣。
【问题讨论】:
-
built-in operator[](long, const char *)...那是...这是怎么回事...? -
据我所知,应该没有歧义。你用什么编译器?
-
请问什么版本的C++
-
@bolov timsong-cpp.github.io/cppwp/n4659/over.built#14
T& operator[](std::ptrdiff_t, T*);,不是吗?
标签: c++ language-lawyer