【发布时间】:2018-06-23 08:24:24
【问题描述】:
最近,我尝试使用转换运算符来替代operator []。
喜欢下面的代码:
#include <iostream>
class foo
{
public:
using type = int[1];
public:
operator type &() { return data; }
operator type const &() const { return data; }
private:
type data;
};
int main()
{
foo f;
f[0] = 1; // error happens here
std::cout << f[0] << std::endl;
return 0;
}
我发现它适用于 G++,但不适用于 MSVCv141(2017)。
MSVC 报告:
error C2593: 'operator [' is ambiguous
note: could be 'built-in C++ operator[(foo::type, int)'
note: or 'built-in C++ operator[(const foo::type, int)'
note: while trying to match the argument list '(foo, int)'
那是 MSVC 的错误还是其他什么?以及如何解决?
【问题讨论】:
-
您的错误在于假设语言考虑了
f[0]的结果将如何使用。简单地说,它没有。 -
@StoryTeller 似乎不是那个问题。上面的代码在 G++ 中工作。如果我使用
operator int *() { return data; }和operator int const *() const { return data; }。没有错误。 -
很好,添加了语言律师标签。一般来说,“编译器 X 接受它”不是正确性的论据。如果这是 MSVC 实际上是正确的罕见情况,我不会感到惊讶,但只有时间和一些好的答案会证明一切。
-
@StoryTeller 你说得对,谢谢。而且我对C++标准不熟悉,希望有人能帮忙。
标签: c++ visual-c++ language-lawyer