使用模板时的C ++类型检查

时间:2016-12-22 22:51:23

标签: c++ class templates operator-overloading

我有一个如此定义的链接列表类,

template <typename Bin> 
    class LinkedList {
    ...
    struct node{
        Bin value;
        ...
    };
...
};

并且在那里我想覆盖==运算符以检查两个列表是否相等。我已经设置了它并且适用于类型相同的情况。 e.g。

LinkedList<int> a;
LinkedList<int> b;
a == b;

工作正常,但如果在不同类型之间进行比较,则会出现编译器错误。除了假设不会比较不匹配的类型之外,还有其他解决方法吗?

1 个答案:

答案 0 :(得分:2)

#include <type_traits>

template<class T>
  struct List
  {

  };

template<class L, class R> 
  auto operator==(const List<L>& l, const List<R>& r)
  -> decltype(std::declval<L>() == std::declval<R>())
{
  bool same = true;
  // run through l and r comparing elements
  // this function will only expand if there is a valid comparison
  // between an L and an R

  return same;
}


int main()
{
  List<int> x;
  List<double> y;

  auto same = x == y;
}