我有一个模板类 A
和一个内部类 B
。我想有一个 friend == 运算符。但是,以下代码无法编译。它说,无法推断模板参数“T”
#include <iostream>
template<typename T>
struct A
{
struct B
{
T b;
template<typename T2>
friend bool operator == (const typename A<T2>::B& b1, const typename A<T2>::B& b2);
};
B b;
};
template<typename T>
bool operator == (const typename A<T>::B& b1, const typename A<T>::B& b2)
{
return b1.b == b2.b;
}
int main() {
A<int>::B b1, b2;
b1.b = 3;
b2.b = 2;
std::cout << (b1 == b2) << std::endl;
return 0;
}
我必须有友元版本,因为其中一种 STL 算法调用它的方式会导致 ==
找不到,否则即使我有 bool operator == (const B& b_) { 返回 b == b_.b; }
有什么办法解决这个问题?
最佳答案
这是一个non-deduced context .
表面上你可以有这样的定义
template<typename AB>
bool operator == (const AB& b1, const AB& b2)
{
return b1.b == b2.b;
}
但它太宽泛了,因为它涵盖了所有 类型。 Yoiy可以这样限制
template<typename AB>
auto operator == (const AB& b1, const AB& b2) ->
std::enable_if_t<std::is_same_v<AB, typename A<decltype(b1.b)>::B>, bool>
{
return b1.b == b2.b;
}
关于c++ - 模板类友元函数的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55837316/