如何为引用参数定义模板函数,为指针参数定义相同的函数

时间:2012-05-11 12:05:21

标签: c++ templates boost stl

我想定义一个用于名称比较的模板化仿函数,它也会引用参考 作为指针。我想将它用于元素容器上的普通find_if以及指针容器(不幸的是,ptr_vector等不是一个选项)。

到目前为止,我找到的最佳解决方案如下:

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;
};

对于不知道enable_if的人来说,这看起来很难看,也很难理解。 是否有一种更简单的方法来编写这样的函子来获取指针和引用?

2 个答案:

答案 0 :(得分:3)

可以这么简单:

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; }

答案 1 :(得分:1)

实现getName成员函数的类是否返回除std :: string之外的其他内容?如果没有,您可以删除一个模板参数。

这就是我实现仿函数的方法:

class by_name
{
  public:
    by_name(const std::string& name) :
      Name(name) {}

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

    template <class T>
    bool operator()(T* pX) const
    {
      if (!pX)  // how do you handle a null ptr?
        return false;
      (*this)(*pX); // @Luc Danton 
    }

  private:
    std::string Name;
};

如果指针版本实现为

bool operator(T const* pX) const {}

gcc因某种原因选择实例化

bool operator(T const& pX) const with [T = A*]

使用gcc 4.6.1编译和测试了仿函数。

相关问题