std::mem_fun
From 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で削除) |
メンバ関数ラッパーオブジェクトを作成します。テンプレート引数からターゲット型を推論します。ラッパーオブジェクトは、その operator() の最初のパラメータとして、型Tのオブジェクトへのポインタを期待します。
この関数および関連する型は、より汎用的な std::mem_fn および std::bind に置き換えられる形で、C++11 で非推奨となり、C++17 で削除されました。これらはどちらもメンバ関数から呼び出し可能なアダプタ互換の関数オブジェクトを作成します。
目次 |
[編集] パラメータ
| 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 など。 recent compilers, e.g. 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); // 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で削除) |
オブジェクトへの参照で呼び出し可能な、メンバ関数へのポインタからラッパーを生成する (関数テンプレート) |