std::mem_fun
來自 cppreference.com
定義於標頭檔案 <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 相容的編譯模式:例如使用 -std=c++11 的 g++/clang++,使用 /std:c++11 的 cl 等。在最新的編譯器(例如 gcc-12)上,如果不是在 C++98 模式下編譯,可能會發出“deprecated declaration”警告。
執行此程式碼
#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 > 201100 int data{42}; #else int 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); // Error: mem_fun supports only member functions // without parameters or with only one parameter. // Thus, std::mem_fn is a better alternative: auto p2 = std::mem_fn(&S::two_args); p2(s, 1, 2); // auto pd = std::mem_fun(&S::data); // Error: pointers to data members are not supported. // Use std::mem_fn instead: 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 中已移除) |
從成員函式指標建立包裝器,可使用物件引用呼叫 (函式模板) |