【问题标题】:C++ type checking when using templates使用模板时的 C++ 类型检查
【发布时间】:2017-05-08 15:32:40
【问题描述】:

我有一个这样定义的链表类,

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

在那里我想覆盖 == 运算符来检查两个列表是否相等。我已经设置好它并适用于类型相同的情况。例如

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

工作得很好,但如果在不同类型之间进行比较,我会收到编译器错误。除了假设不会比较不匹配的类型之外,还有其他解决方法吗?

【问题讨论】:

  • 所以您是说您希望能够比较具有不同类型的列表?
  • @Brian:例如比较 LinkedList&lt;int&gt;LinkedList&lt;long&gt; 对我来说似乎很有意义。

标签: c++ class templates operator-overloading


【解决方案1】:
#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多