How to define a template function for a reference parameter and the same function for a pointer parameter

advertisements

I want to define a templated functor for name comparison, that takes references as well as pointers. I want to use this for a normal find_if on a container of elements as well as for a container of pointers (unfortunately ptr_vector or the like is not an option).

The best solution I have found so far is the following.

template <typename U>
class by_name{
  public:
    by_name(U const& pName):mName(pName) {}

    template <class T>
    typename boost::disable_if_c<boost::is_pointer<T>::value, bool>::type
    operator()(T const& pX){ return pX.getName()== mName;}

    template <class T>
    typename boost::enable_if_c<boost::is_pointer<T>::value, bool>::type
    operator()(T pX){ return pX->getName()== mName;}

private:
    U mName;
};

This looks quite ugly and very hard to understand for people not knowing enable_if. Is there an easier way to write such a functor taking pointer and reference alike?


It can be as simple as:

template <class T>
bool operator()(T const& rX) const { return rX.getName() == mName; }

template <class T>
bool operator()(T* const pX) const { return pX->getName() == mName; }