简体   繁体   中英

“No match operator==” error when using std::equal and namespace

I get compile error ("no match for operator==") when using std::equal and my classes are define in separate namespaces (proper operators are defined).

This is my working example using std::equal but without namespace and there is no compile error

#include <vector>
#include <algorithm>

struct K {
    int a;
};

struct V {
    int b;
};


inline bool operator== (const K& lhs, const V& rhs) {
    return lhs.a == rhs.b;
}

inline bool operator== (
const std::vector<K>& lhs, const std::vector<V>& rhs) {
    return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}

But when I use namespace for my classes there is "no match operator" error

#include <vector>
#include <algorithm>


namespace nk {
  struct K {
    int a;
};  
}

namespace nv {
  struct V {
    int b;
};  
}

inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
    return lhs.a == rhs.b;
}

inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
    return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}

/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/bits/stl_algobase.h:1107:22: error: no match for 'operator==' (operand types are 'const nk::K' and 'const nv::V')

Also there is no error when std::equal replaced with simple loop (compare operators work well in this case):

inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
    if (lhs.size() != rhs.size()) {
        return false;
    }

    for(std::size_t i=0; i<lhs.size(); i++) {
        if (!(lhs[i]==rhs[i])) {
            return false;
        }
    }
    return true;
}

Codes are tested with Compiler Explorer and GCC 10.0.2 (I've also tested other GCC versions)

The problem is that the library like std::equal can't find the operator== defined in global scope.

You can move operator== into either the namespace where K or V is defined to validate ADL . (PS your 1st code snippet works because of ADL too.)

Eg

namespace nk {
  struct K {
    int a;
  };  
}

namespace nv {
  struct V {
    int b;
  };  

  inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
      return lhs.a == rhs.b;
  }
}

LIVE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM