最近,我尝试使用转换运算符作为替代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;
}
Run Code Online (Sandbox Code Playgroud)
我发现它适用于G ++,但不适用于MSVC v141(2017).
MSVC报道:
error C2593: 'operator [' is ambiguous
note: could be 'built-in C++ operator[(foo::type, int)'
note: or 'built-in C++ …Run Code Online (Sandbox Code Playgroud)