std::mem_fun
| ヘッダ <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() のオブジェクトへのポインタを期待します。
std::mem_fun_t<Res,T>(f) または std::const_mem_fun_t<Res,T>(f) を呼び出します。std::mem_fun1_t<Res,T,Arg>(f) または std::const_mem_fun1_t<Res,T,Arg>(f) を呼び出します。この関数および関連する型は 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 > 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); // エラー:mem_fun はパラメータなしまたは1つのパラメータのみの // メンバ関数のみをサポートします。 // したがって、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で削除)
|
オブジェクトへの参照で呼び出し可能な、メンバ関数ポインタからのラッパーを作成する
(関数テンプレート) |