gpt4 book ai didi

C++ 模板内部类友元运算符重载

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

我正在尝试为 operator!= 实现一个重载,它比较两个不同类型的对象(InnerAInnerB)。这两种类型都定义为模板类 (Outer) 中的嵌套类。重载需要成为两个类的友元,因为它访问每个类的私有(private)字段。

template<typename Type> class Outer
{
public:
class InnerA;
class InnerB;
};


template<typename Type> bool operator!=(const typename Outer<Type>::InnerA& lhs, const typename Outer<Type>::InnerB& rhs);


template<typename Type> class Outer<Type>::InnerA
{
const int val = 0;
friend bool operator!=<>(const InnerA& lhs, const typename Outer<Type>::InnerB& rhs);
};


template<typename Type> class Outer<Type>::InnerB
{
const int val = 1;
friend bool operator!=<>(const typename Outer<Type>::InnerA& lhs, const InnerB& rhs);
};


template<typename Type> bool operator!=(const typename Outer<Type>::InnerA& lhs, const typename Outer<Type>::InnerB& rhs)
{
return lhs.val != rhs.val;
}


int main()
{
bool b = Outer<int>::InnerA() != Outer<int>::InnerB();
}

上面的代码编译失败,发出:

 In instantiation of 'class Outer<int>::InnerA':
34:33: required from here
15:17: error: template-id 'operator!=<>' for 'bool operator!=(const Outer<int>::InnerA&, const Outer<int>::InnerB&)' does not match any template declaration
In instantiation of 'class Outer<int>::InnerB':
34:57: required from here
22:17: error: template-id 'operator!=<>' for 'bool operator!=(const Outer<int>::InnerA&, const Outer<int>::InnerB&)' does not match any template declaration
In function 'int main()':
34:35: error: no match for 'operator!=' (operand types are 'Outer<int>::InnerA' and 'Outer<int>::InnerB')
34:35: note: candidate is:
26:30: note: template<class Type> bool operator!=(const typename Outer<Type>::InnerA&, const typename Outer<Type>::InnerB&)
26:30: note: template argument deduction/substitution failed:
34:57: note: couldn't deduce template parameter 'Type'

虽然可能有更好的方法来实现类似的结果,但我很好奇我的代码到底出了什么问题。谢谢!

最佳答案

template<typename Type> class Outer<Type>::InnerA
{
friend bool operator!=(const InnerA& lhs, const typename Outer<Type>::InnerB& rhs) { return true; }
};
template<typename Type> class Outer<Type>::InnerB
{
friend bool operator!=(const typename Outer<Type>::InnerA& lhs, const InnerB& rhs) { return true; }
};

这些是非模板 friend 。他们也有冲突。所以实现其中一个,省略另一个。

它们将通过 ADL 找到。

关于C++ 模板内部类友元运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50382081/

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