C++ Library Extensions 2022.12.09
To help learn modern C++ programming
10-mem_fn.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6template<typename ReturnType, typename ClassType, typename... Types>
8{
9 private:
10 ReturnType (ClassType::*mem_ptr)(Types...);
11 public:
12 mem_func_call_wrapper( ReturnType (ClassType::*mptr)(Types...) ):
13 mem_ptr {mptr} { }
14
15 template<typename TypeClass, typename... ArgTypes>
16 ReturnType operator()(TypeClass&& obj, ArgTypes&&... args) const
17 {
18 return (obj.*mem_ptr)( std::forward<ArgTypes>(args)...);
19 }
20};
21
22template<typename ReturnType, typename ClassType, typename... Types>
23mem_func_call_wrapper<ReturnType, ClassType, Types...> mem_fn(ReturnType (ClassType::*mptr)(Types...))
24{
25 return { mptr };
26}
27
28class DummyClass
29{
30 private:
31 int m_value;
32 public:
33
34 DummyClass(int value) : m_value { value } { }
35
36 int sum(int a, int b)
37 {
38 return m_value * ( a + b );
39 }
40
41 int pro(int a, int b)
42 {
43 return m_value * (a * b);
44 }
45};
46
48{
49 DummyClass d{10};
50
51 auto mf = mem_fn( &DummyClass::sum );
52
53 auto rlt = mf(d, 2, 3); // d.sum(2, 3);
54
55 stream << "rlt = " << rlt << endl;
56
57 auto mf_pro = mem_fn( &DummyClass::pro );
58
59
60 stream << "d.pro(2, 3) = " << mf_pro(d, 2, 3) << endl;
61
62}
63
64int main()
65{
67}
68
69
tpf::sstream stream
Definition: 10-mem_fn.cpp:3
void test_mem_fn()
Definition: 10-mem_fn.cpp:47
mem_func_call_wrapper< ReturnType, ClassType, Types... > mem_fn(ReturnType(ClassType::*mptr)(Types...))
Definition: 10-mem_fn.cpp:23
auto endl
Definition: 10-mem_fn.cpp:4
int main()
Definition: 10-mem_fn.cpp:64
int pro(int a, int b)
Definition: 10-mem_fn.cpp:41
int sum(int a, int b)
Definition: 10-mem_fn.cpp:36
DummyClass(int value)
Definition: 10-mem_fn.cpp:34
mem_func_call_wrapper(ReturnType(ClassType::*mptr)(Types...))
Definition: 10-mem_fn.cpp:12
ReturnType operator()(TypeClass &&obj, ArgTypes &&... args) const
Definition: 10-mem_fn.cpp:16
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.