Containers of reference_wrappers (comparison operators required?)

Posted by kloffy on Stack Overflow See other posts from Stack Overflow or by kloffy
Published on 2010-04-09T23:20:11Z Indexed on 2010/04/09 23:23 UTC
Read the original article Hit count: 371

Filed under:
|
|
|
|

If you use stl containers together with reference_wrappers of POD types, the following code works just fine:

int i = 3;
std::vector< boost::reference_wrapper<int> > is;
is.push_back(boost::ref(i));
std::cout << (std::find(is.begin(),is.end(),i)!=is.end()) << std::endl;

However, if you use non-POD types such as (contrived example):

struct Integer
{
 int value;

 bool operator==(const Integer& rhs) const
 {
  return value==rhs.value;
 }

 bool operator!=(const Integer& rhs) const
 {
  return !(*this == rhs);
 }
};

It doesn't suffice to declare those comparison operators, instead you have to declare:

bool operator==(const boost::reference_wrapper<Integer>& lhs, const Integer& rhs)
{
 return boost::unwrap_ref(lhs)==rhs;
}

And possibly also:

bool operator==(const Integer& lhs, const boost::reference_wrapper<Integer>& rhs)
{
 return lhs==boost::unwrap_ref(rhs);
}

In order to get the equivalent code to work:

Integer j = { 0 };
std::vector< boost::reference_wrapper<Integer> > js;
js.push_back(boost::ref(j));
std::cout << (std::find(js.begin(),js.end(),j)!=js.end()) << std::endl;

Now, I'm wondering if this is really the way it's meant to be done, since it seems impractical. It just seems there should be a simpler solution, e.g. templates:

template<class T>
bool operator==(const boost::reference_wrapper<T>& lhs, const T& rhs)
{
 return boost::unwrap_ref(lhs)==rhs;
}

template<class T>
bool operator==(const T& lhs, const boost::reference_wrapper<T>& rhs)
{
 return lhs==boost::unwrap_ref(rhs);
}

There's probably a good reason why reference_wrapper behaves the way it does (possibly to accomodate non-POD types without comparison operators?). Maybe there already is an elegant solution and I just haven't found it.

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl