functional_mem_fun
functional_mem_fun (멤버 함수 포인터를 함수 객체로 만드는 함수)
이 페이지는 C++ 표준 라이브러리의 std::mem_fun 함수 템플릿에 대해 설명해요. std::mem_fun은 멤버 함수 포인터를 받아 그 멤버 함수를 호출하는 함수 객체를 만들어 주는데, C++11에서 더 일반적인 std::mem_fn과 std::bind로 대체되었어요.
출처: cppreference
본문
<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 타입 객체에 대한 포인터를 기대해요.
이 함수와 관련 타입들은 C++11에서 폐기(deprecated)되었고 C++17에서 제거되었어요. 더 일반적인 std::mem_fn과 std::bind가 멤버 함수로부터 호출 가능한 어댑터 호환 함수 객체를 만들어 주기 때문이에요.
매개변수 (Parameters)
| f | - | 래퍼를 만들 멤버 함수 포인터 |
|---|
반환값 (Return value)
f를 감싸는 함수 객체.
예외 (Exceptions)
구현 정의 예외를 던질 수 있어요.
참고 (Notes)
std::mem_fun과 std::mem_fun_ref의 차이는 전자는 객체에 대한 포인터를 기대하는 함수 래퍼를 만들고, 후자는 참조를 기대하는 래퍼를 만든다는 점이에요.
예제 (Example)
std::mem_fun 사용법을 보여주고 std::mem_fn과 비교해요. C++11/14 호환 컴파일 모드가 필요할 수 있어요: g++/clang++에서 -std=c++11, cl에서 /std:c++11 등. 최신 컴파일러(예: 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
같이 보기 (See also)
| mem_fn (C++11) | 멤버 포인터로부터 함수 객체를 생성해요 (함수 템플릿) [edit] |
|---|---|
| mem_fun_ref (C++11에서 폐기, C++17에서 제거) | 객체에 대한 참조로 호출할 수 있는 멤버 함수 포인터로부터 래퍼를 생성해요 (함수 템플릿) [edit] |