gpt4 book ai didi

c++ - 是否可以为模板类中的嵌套模板类定义非交换运算符?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:49 25 4
gpt4 key购买 nike

我有这个代码:

template<typename T>
class A
{
public:
template<typename innerT>
class B
{
};
};

我想在 A ::B 和“int”上声明“==”运算符,以便它根据整数是第一个还是第二个返回不同的东西。

测试方法如下所示:

#include <iostream>
int main(int argc, char** argv)
{
A<float>::B<double> b;
std::cout << (b == 2) << " is different from " << (2 == b);
}

我在想这样的事情:

template<typename T, typename innerT> bool operator==(typename A<T>::B<innerT> & one, int two)
{ return true; }

template<typename T,typename innerT> bool operator==(int one, typename A<T>::B<innerT> & two)
{ return false; }

但它不起作用。

最佳答案

你可以把他们移到类 A 作为 friend :

template<typename T>
class A
{
public:
template<typename innerT>
class B
{
};

template<typename innerT>
friend bool operator==(A::B<innerT> & one, int two)
{ return true; }

template<typename innerT>
friend bool operator==(int one, A::B<innerT> & two)
{ return false; }
};

Live example

关于c++ - 是否可以为模板类中的嵌套模板类定义非交换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21030063/

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