gpt4 book ai didi

c++ - 消除 operator[] 绑定(bind)的歧义

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:53 24 4
gpt4 key购买 nike

我正在尝试从一个开源项目编译代码,但我遇到了一个问题,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 的定义替换为其特定实例,问题变得更加清晰:

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++ - 消除 operator[] 绑定(bind)的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/539536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com