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

时间:2014-01-09 20:06:21

标签: c++ templates operator-overloading

我有这段代码:

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

我想在A&lt; T&gt; :: B&lt; innerT&gt;上声明“==”运算符和“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; }

但它不起作用。

1 个答案:

答案 0 :(得分:2)

您可以将他们作为朋友转移到班级A

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