[C++] mem_fn
Updated:
개요
- 멤버 함수를 객체로 변환
- 람다로도 동일한 역할 가능
코드
#include <functional>
#include <iostream>
using namespace std;
class Test {
private:
int i;
public:
Test(const int &i) : i(i){};
~Test() = default;
int GetI() const { return this->i; }
void SetI(const int &i) { this->i = i; }
};
int main() {
Test t(1);
auto f1 = mem_fn(&Test::GetI);
auto f2 = mem_fn(&Test::SetI);
cout << f1(t) << endl;
auto f3 = [](const Test &t) { return t.GetI(); };
f2(t, 2);
cout << f3(t) << endl;
return 0;
}
실행 결과
1
2