繁体   English   中英

如何为参考参数定义模板函数和为指针参数定义相同的函数

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

我想定义一个用于名称比较的模板化函子,该函子需要引用和指针。 我想将其用于元素容器上的普通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进行编译和测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM