我正在尝试从开源项目编译代码,但遇到了一个问题,其中 gcc 声称特定代码行的解释不明确。问题涉及到一个模板类和这两个方法:
template <class X>
class A {
public:
X& operator[] (int i) { ... }
operator const X* () { ... }
};
当按照以下方式使用时:
A<B*> a;
B* b = a[i];
gcc 提示 a[i] 的解析不明确。通过用 A 的具体实例替换 A 的定义,问题变得更加清晰:
class A_B {
public:
B*& operator[] (int i) { ... }
operator B* const * () { ... }
};
问题是有两种解释 B* b = a[i] 的方法:
// First interpretation (array-like behaviour first)
B*& b1 = a[i];
B* b2 = (B*) b1;
// Second interpretation (casting behaviour first)
B* const * b1 = (B* const *) a;
B* b2 = b1[a];
我的问题是这样的:是否有某种方法可以提供首选解释,最好是在没有显式强制转换的情况下使强制转换版本变得不可取,这样我就不必修改尝试调用 A[] 的每一行?我意识到这种解释在理论上是不明确的,但我知道代码的意图是什么,并且我想以最小的更改将其传达给编译器。
编辑:看来我的示例不会导致相关错误,因此我没有正确总结原始代码,也没有正确识别问题。我会尝试先找到一个产生问题的示例,抱歉各位。
最佳答案
以下代码使用 g++ 3.x 进行编译。我认为您对问题的分析不正确,但无论如何您可以发布您收到的错误消息吗?
template <class X>
struct A {
X& operator[] (int i) { static X x; return x; }
operator const X* () { return 0; }
};
class B {};
int main() {
A<B*> a;
B* b = a[0];
}
关于c++ - 消除运算符[]绑定(bind)的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/539536/