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

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

本文关键字:函数 定义 参数 指针 引用      更新时间:2023-10-16

我想定义一个用于名称比较的模板化函子,它也需要引用作为指针。我想将其用于元素容器上的正常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的人来说很难理解。有没有更简单的方法来编写这样的函子,同时接受指针和引用?

它可以

像这样简单:

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

实现 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 编译和测试。