Ubuntu Pastebin

Paste from anpok at Fri, 3 Jul 2015 08:02:23 +0000

Download as text
 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
#include <iostream>
#include <functional>

template<typename Ret, typename ...Params>
struct sick
{
    template<std::function<Ret(Params...)>*fun>
    struct man
    {
        static Ret call_it(Params... param)
        {
            return (*fun)(param...);
        }
    };
};

void needs_a_void_int(void (*fun)(int))
{
    fun(123);
}

void needs_a_int_int_int(int (*fun)(int, int))
{
    std::cout << fun(123,231) << std::endl;
}

class Example
{
public:
    void bla(int x)
    {
        std::cout <<__FUNCTION__ << ' '<< x << std::endl;
    }
int plus(int y, int x)
    {
        std::cout <<__FUNCTION__ << y << '+'<< x << std::endl;
        return x+y;
    }
};

// the following functions need to be global
// otherwise the address would not be a constant expression
// (in c++03 they would have have external linkage)
std::function<void(int)> bla;
std::function<int(int,int)> plus;

int main()
{

    Example obj;
    bla = [&obj](int value)->void { obj.bla(value); };
    plus = [&obj](int v1, int v2)->int { return obj.plus(v1,v2); };

    // with function traits that could be a macro
    needs_a_void_int(&sick<void,int>::man<&bla>::call_it);
    needs_a_int_int_int(&sick<int,int,int>::man<&plus>::call_it);
}
Download as text