2

I intend to define a custom operator== for boost::tuple

#include <iostream>
#include <vector>
#include <boost/tuple/tuple.hpp>
//#include <boost/tuple/tuple_comparison.hpp>

/*namespace boost { namespace tuples {*/
bool operator==(const boost::tuple<int>&, const boost::tuple<int>&){
  return false;    
}
/*}}*/

int main(){
  boost::tuple<int> t, u;      
  std::vector<boost::tuple<int> > vec;

  std::cout << (t == u); // [1]

  find(vec.begin(), vec.end(), t); // [2]
}

While this works for [1], it fails for [2] with the following error:

/usr/local/include/c++/4.9.2/bits/predefined_ops.h:191:17: error:
no match for 'operator==' (operand types are 'boost::tuples::tuple<int>'
and 'const boost::tuples::tuple<int>')
  { return *__it == _M_value; }

So, my question is, why does the compiler not look for operator== in the global namespace in the case of std::find.

NB: it works if i place the operator== in namespace boost::tuples as shown in the comments above.

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
user1055604
  • 1,624
  • 11
  • 28
  • Rather than editing this older solved question, please post a new one and if you think it's helpful include a link to this question. – Bill Lynch Apr 03 '15 at 15:00

2 Answers2

4

You should include an additional file:

#include "boost/tuple/tuple_comparison.hpp"

Since the operators are defined in a separate header.

The reason that it doesn't look in the global namespace is due to the rules of ADL, which will only look in the boost::tuples namespace (where the tuple is defined), and the std namespace.

Read What is “Argument-Dependent Lookup” (aka ADL, or “Koenig Lookup”) for more info

Community
  • 1
  • 1
Dave S
  • 20,507
  • 3
  • 48
  • 68
  • hey.. the link you pointed to says and i quote `The algorithm (ADL) tells the compiler to not just look at local scope, but also the namespaces that contain the argument's type`... isn't the custom `operator ==` here essentially in the local scope or is there something i am missing? – user1055604 Apr 03 '15 at 18:01
  • @user1055604 The problem is that the failure is occurring when it's in std::find's scope, not your own. So in this case, it would only search the boost and std namespaces. – Dave S Apr 04 '15 at 02:18
2

ADL. When you just use operator == in your code - namespace boost::tuples and global namespace are processed. But, since find is in std namespace only std and boost::tuples will be processed.

ForEveR
  • 55,233
  • 2
  • 119
  • 133