Search code examples
c++stlboostcontainerstr1

Containers of reference_wrappers (comparison operators required?)


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

int i = 0;
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 like (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 the comparison operators above, aditionally 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's somewhat 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.


Solution

  • Does the example above work when you declare the original comparison routines as such:

    friend bool operator==(const Integer& lhs, const Integer& rhs)
    {
        return lhs.value == rhs.value;
    }
    
    friend bool operator!=(const Integer& lhs, const Integer& rhs)
    {
        return !(lhs == rhs);
    }
    

    Note that declaring a friend comparison routine in the class is not the same as declaring a member function comparison routine, which is why these may work while your original code may not.