language: C++ 4.7.2 (gcc-4.7.2)
date: 239 days 21 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
 
struct Function 
{
    virtual ~Function() {}
    virtual void operator()() = 0;
};
 
template <typename Class, typename ARG1>
struct MemberFunction1 : public Function
{
    typedef void (Class::*MEM_FUNC)(ARG1);
    explicit MemberFunction1(Class * obj, MEM_FUNC func, ARG1 arg1) :  m_object(obj), m_func(func), m_arg1(arg1) {}
 
    virtual void operator()()
    {
        (m_object->*m_func)(m_arg1);
    }
 
    Class *  m_object;
    MEM_FUNC m_func;    
    ARG1     m_arg1;
};
 
struct FunctionStorage
{
    explicit FunctionStorage(Function * func) : m_func(func) {}
 
    virtual ~FunctionStorage()
    {
        if (m_func)
        {
            delete m_func;
            m_func = 0;
        }
    }
    
    void call() { (*m_func)(); }
    Function * m_func;
};
 
struct MemberFunction : public FunctionStorage
{
    template <typename Class, typename ARG1>
    MemberFunction(Class * obj, void (Class::*func)(ARG1), ARG1 arg1) : FunctionStorage(new MemberFunction1<Class, ARG1>(obj, func, arg1)) {}
};
 
 
class Foo 
{
public:
    void funcWithParam(int value)
    {
        std::cout << "foo::funcWithParam(" << value << ")\n";
    }
    void funcWithParam(const char * msg)
    {
        std::cout << "foo::funcWithParam(" << msg << ")\n";
    }
};
 
int main()
{
    Foo f;    
    MemberFunction(&f, &Foo::funcWithParam, 5).call();
    MemberFunction(&f, &Foo::funcWithParam, "hello").call();
    return 0;
}