gpt4 book ai didi

c++ - 潜在的 g++ 模板错误?

转载 作者:IT老高 更新时间:2023-10-28 23:10:13 25 4
gpt4 key购买 nike

我遇到了一些我认为应该编译但没有编译的代码。所以我希望 SO 的一些本地标准专家可以提供帮助:-)。

我基本上有一些类似这样的代码:

#include <iostream>

template <class T = int>
class A {
public:
class U {
};

public:
U f() const { return U(); }
};

// test either the work around or the code I want...
#ifndef USE_FIX
template <class T>
bool operator==(const typename A<T>::U &x, int y) {
return true;
}
#else
typedef A<int> AI;
bool operator==(const AI::U &x, int y) {
return true;
}
#endif

int main() {
A<int> a;
std::cout << (a.f() == 1) << std::endl;
}

所以,描述一下这里发生了什么。我有一个类模板 (A),它有一个内部类 (U) 和至少一个可以返回该内部类实例的成员函数 (f ()).

然后我尝试创建一个 operator== 函数,该函数将此内部类型与其他类型(在本例中为 int 进行比较,但它似乎不是重要)。

USE_FIXnot 定义时,我收到以下错误:

test.cc: In function 'int main()':
test.cc:27:25: error: no match for 'operator==' in 'a.A<T>::f [with T = int]() == 1'

这看起来很奇怪,因为我显然(我认为)定义了一个模板化的 operator== 应该涵盖这一点,事实上,如果我只是为编译器做一些工作(启用 USE_FIX ),然后我不再收到错误消息。不幸的是,“修复”通常不起作用,仅适用于模板的特定实例化。

这应该像我预期的那样工作吗?还是根本不允许这样做?

顺便说一句:如果重要的话,我使用的是 gcc 4.5.2。

最佳答案

const typename A<T>::U &x 的问题是U是依赖类型,编译器无法推断 T从论点(这是非推断上下文之一)。

例如,您可以有两个特化 A :

class X { };
class Y { };
class Z { };

template <> class A<X> {
public:
typedef Z U;
};

template <> class A<Y> {
public:
typedef Z U;
};

如果你再打电话:

Z a;
a == 1;

编译器应该推导出什么 T作为? X ? Y ?

在这种特殊情况下,一个解决方案是声明 operator==作为类模板中的非模板 friend :

template <class T = int>
class A {
public:
class U {
};

friend bool operator==(const U& x, int y) {
return true;
}

public:
U f() const { return U(); }
};

关于c++ - 潜在的 g++ 模板错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4677728/

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