std::mem_fun
来自cppreference.com
< cpp | utility | functional
在标头 <functional> 定义 | ||
template<class Res, class T > std::mem_fun_t<Res,T> mem_fun( Res (T::*f)()); | (1) | (C++11 弃用) (C++17 移除) |
template<class Res, class T > std::const_mem_fun_t<Res,T> mem_fun( Res (T::*f)()const); | (1) | (C++11 弃用) (C++17 移除) |
template<class Res, class T, class Arg > std::mem_fun1_t<Res,T,Arg> mem_fun( Res (T::*f)(Arg)); | (2) | (C++11 弃用) (C++17 移除) |
template<class Res, class T, class Arg > std::const_mem_fun1_t<Res,T,Arg> mem_fun( Res (T::*f)(Arg)const); | (2) | (C++11 弃用) (C++17 移除) |
创建成员函数包装器对象,从模板实参推导目标类型。包装器对象期待以指向 T
类型对象的指针作为其 operator() 的首个参数。
此函数与相关类型于 C++11 弃用并于 C++17 移除,为了让位给更通用的 std::mem_fn 与 std::bind,它们都能从成员函数创建可调用的兼容适配器的函数对象。
目录 |
[编辑]参数
f | - | 要创建包装器的成员函数指针 |
[编辑]返回值
包装 f
的函数对象。
[编辑]异常
可能会抛出由实现定义的异常。
[编辑]注解
std::mem_fun 与 std::mem_fun_ref 的区别是前者产生的函数包装器期待对象指针,而后者期待引用。
[编辑]示例
演示 std::mem_fun
的用法,并将其与 std::mem_fn 进行比较。可能必须使用 C++11/14 兼容编译模式:g++/clang++ 带 -std=c++11,cl 带 /std:c++11 等。在近期的编译器(如 gcc-12)上,如果不在 C++98 模式中编译,则可能给出 "已弃用声明" 的警告。
运行此代码
#include <functional>#include <iostream> struct S {int get_data()const{return data;}void no_args()const{std::cout<<"void S::no_args() const\n";}void one_arg(int){std::cout<<"void S::one_arg()\n";}void two_args(int, int){std::cout<<"void S::two_args(int, int)\n";}#if __cplusplus > 201100int data{42};#elseint data; S(): data(42){}#endif}; int main(){ S s; std::const_mem_fun_t<int, S> p = std::mem_fun(&S::get_data);std::cout<<"s.get_data(): "<< p(&s)<<'\n'; std::const_mem_fun_t<void, S> p0 = std::mem_fun(&S::no_args); p0(&s); std::mem_fun1_t<void, S, int> p1 = std::mem_fun(&S::one_arg); p1(&s, 1); #if __cplusplus > 201100// auto p2 = std::mem_fun(&S::two_args); // 错误: mem_fun 只支持没有形参或只有一个形参的成员函数。// 因此,std::mem_fn 是更好的替代品:auto p2 =std::mem_fn(&S::two_args); p2(s, 1, 2); // auto pd = std::mem_fun(&S::data); // 错误: 不支持数据成员指针。// 换用 std::mem_fn:auto pd =std::mem_fn(&S::data);std::cout<<"s.data = "<< pd(s)<<'\n';#endif}
可能的输出:
s.get_data(): 42 void S::no_args() const void S::one_arg(int) void S::two_args(int, int) s.data = 42
[编辑]参阅
(C++11) | 从成员指针创建出函数对象 (函数模板) |
(C++11 弃用)(C++17 移除) | 从成员函数指针创建包装器,可以一个对象引用调用 (函数模板) |