C++ 运算符==()使用模板

C++ 运算符==()使用模板,c++,c++11,templates,C++,C++11,Templates,编辑:序言:我是自己无知的受害者,也是深夜编码的受害者。 我正在使用模板编写一个模板类。它有一个迭代器,这意味着我需要提供一个适当模板化的操作符==()。这就是我遇到麻烦的地方 代表性代码示例如下: #include <iostream> #include <typeinfo> using namespace std; namespace detail { template <typename T> class foo {}; template

编辑:序言:我是自己无知的受害者,也是深夜编码的受害者。


我正在使用模板编写一个模板类。它有一个迭代器,这意味着我需要提供一个适当模板化的
操作符==()
。这就是我遇到麻烦的地方

代表性代码示例如下:

#include <iostream>
#include <typeinfo>

using namespace std;

namespace detail {
  template <typename T> class foo {};
  template <typename T> class bar {};
}

template <template<class> class A, template<class> class B>
struct basic_thing {
  template <typename T> using target_type = A<B<T>>;

  target_type<float> fmember;
  target_type<int>   imember;

  struct iterator {
    bool equal (const iterator& other) { return true; }
  };

  iterator begin () { return iterator{}; }
  iterator end   () { return iterator{}; }
};

template <template<class> class A, template<class> class B>
bool operator== (const typename basic_thing<A, B>::iterator& lhs, const typename basic_thing<A, B>::iterator& rhs) {
  return lhs.equal(rhs);
}

int main ()
{
  using Thing = basic_thing<detail::foo, detail::bar>;

  Thing t;
  cout << typeid(t.fmember).name() << endl;
  cout << typeid(t.imember).name() << endl;

  bool b = (t.begin() == t.end());

  return 0;
}

有哪些正确的方法可以做到这一点?当涉及到模板时,是否有可能?

更简单的方法是直接在结构内部创建它(作为成员或朋友函数):


那太尴尬了。对此我没有任何解释,但我不知何故在脑海中明白了,
operator==()
不能用作类方法。不要再为我深夜编码了!此外,它也很好地解决了这一问题:
foo.cc: In function 'int main()':
foo.cc:39:23: error: no match for 'operator==' (operand types are 'basic_thing<detail::foo, detail::bar>::iterator' and 'basic_thing<detail::foo, detail::bar>::iterator')
   bool b = (t.begin() == t.end());
             ~~~~~~~~~~^~~~~~~~~~
foo.cc:27:6: note: candidate: template<template<class> class A, template<class> class B> bool operator==(const typename basic_thing<A, B>::iterator&, const typename basic_thing<A, B>::iterator&)
 bool operator== (const typename basic_thing<A, B>::iterator& lhs, const typename basic_thing<A, B>::iterator& rhs) {
      ^~~~~~~~
foo.cc:27:6: note:   template argument deduction/substitution failed:
foo.cc:39:32: note:   couldn't deduce template parameter 'template<class> class A'
   bool b = (t.begin() == t.end());
                            ^
template <template<class> class A, template<class> class B>
struct basic_thing {
  // ...
  struct iterator {
    bool equal (const iterator& other) { return true; }

    bool operator ==(const iterator& rhs) const;
    // friend bool operator ==(const iterator& lhs, const iterator& rhs);
  };
};
template <template<class> class A, template<class> class B>
bool operator== (const typename basic_thing<A, B>::iterator& lhs,
                 const typename basic_thing<A, B>::iterator& rhs);
bool b = operator==<detail::foo, detail::bar>(t.begin(), t.begin());