c++ - 类模板上的关系运算符

标签 c++ templates operator-overloading friend

这行不通

template<typename T>
struct foo {
  T t;
};
bool operator==(const foo &lhs, const foo &rhs) { //error, requires template arg
  return lhs.t == rhs.t;
}

这是解决这个问题的正确方法吗?我还想定义运算符 <,>,<=,>=,!= 这样做 template<typename T>所有这些都会很长。

template<typename T>
struct foo {
  T t;
};
template<typename T>
bool operator==(const foo<T> &lhs, const foo<T> &rhs) {
  return lhs.t == rhs.t;
}

最佳答案

解决方案有两种:可以在类内部定义为const成员函数

template<typename T>
struct foo {
  T t;

  bool operator==(const foo &lhs, const foo &rhs) const { return lhs.t == rhs.t; }
  // same for the other relational operators
};

这是有效的,因为在类中你可以使用 foo作为 foo<T> 的简写.

另一种方法是将它们定义为类中的友元非成员函数

template<typename T>
class foo {
  T t;

  friend bool operator==(const foo &lhs, const foo &rhs) const { return lhs.t == rhs.t; }
  // same for the other relational operators
};

如果定义 t作为私有(private)成员(member),那么您实际上需要制作operator==一个friend功能,以便让它获得访问权限。但是请注意,这会产生副作用,因为将它们作为非成员非模板函数注入(inject)到周围的命名空间中。这对依赖于参数的名称查找有一些影响。

关于c++ - 类模板上的关系运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021447/

相关文章:

c++ - 指向 objc 类成员方法的函数指针,用于 C++?

c++ - 同步此事件实现的最佳方式是什么

如果调用 vector ,C++ vector 段错误会导致崩溃

c++ - 一个函数可以同时接受迭代器和反向迭代器作为参数吗

c++ - 重载运算符的递归问题

c++ - 为什么这种打破封装的方式在 C++ 中起作用?

c++ - 我怎样才能创建一个行为与另一种类型一样的类型?

email - 使用 lb-mandrill-connector 环回验证用户 : Uncaught AssertionError: template name should be defined

c++ - () = 类中的运算符重载

c++ - 临时变量被重载的 + 和 += 运算符破坏