对成员函数使用std::ptr_fun
Using std::ptr_fun for a member function
考虑以下内容:
class A
{
public:
bool is_odd(int i)
{
return (i % 2) != 0;
}
void fun()
{
std::vector<int> v2;
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
// fails here
v2.erase(std::remove_if(v2.begin(), v2.end(), std::not1(std::ptr_fun(is_odd))), v2.end());
}
};
上面的代码未能否定is_odd()
的作用,因为它是一个成员函数。对std::ptr_fun()
的调用失败。
我该如何上班?请注意,我希望is_odd()
是一个非静态成员函数。
使用A::is_odd(int)
作为一元谓词存在多个问题,尤其是当它需要与std::not1()
:一起使用时
- 对
A::is_odd(int)
的调用需要两个参数:隐式对象("this
")和可见的int
参数 - 它不是定义
argument_type
和result_type
的函数对象
正确使用此成员函数作为一元谓词需要两个步骤:
- 将成员函数指针适配为合适的函数对象,例如,使用
std::mem_*fun
函数之一 - 使用可能使用
std::bind1st()
的非C++11编译器将第一个参数绑定到合适的对象
使用C++11编译器,事情会容易得多,因为std::bind()
同时处理这两个问题。假设它是从A
的成员使用的:
... std::not1(std::bind(&A::is_odd, this, std::placeholders::_1)) ...
与C++11之前版本的编译器相同的情况有些困难。在std::remove_if()
中的使用看起来像这样:
v2.erase(
std::remove_if(v2.begin(),
v2.end(),
std::not1(std::bind1st(std::mem_fun(&A::is_odd), this))),
v2.end());
只需使is_odd
为静态,就不需要隐式this
参数:
static bool is_odd(int i)
它不使用任何成员变量或其他成员函数。
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 为什么"fun(i)"被推导出为"fun<int&>"而不是"fun<int>",因为"i"是"int"的类型而不是参考?
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr