如何为引用参数定义模板函数,为指针参数定义相同的函数
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 编译和测试。
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义