C++11: polymorphic function objects

 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
#include <functional>
#include <iostream>
#include <cassert>

static void PrintFunction()
{
    std::cout << "PrintFunction" << std::endl;
}

struct PrintFunctor
{
    void operator()() const
    {
        std::cout << "PrintFunctor::operator()()"<< std::endl;
    }
};

int main()
{

     auto lambda1 = []()->void
                    {
                        std::cout << "lambda.. " << std::endl;
                    };

    std::function<void()> func1;

    //  since this is supposed to simulate a function
    //  you can check if this has been assigned to a
    //  callable entity or not by checking it as a boolean
    //  expression or comparing it with nullptr
    //
    assert(!func1)
    assert(func1 == nullptr);

    func1 = lambda1;
    func1();

    func1 = PrintFunction;
    func1();

    PrintFunctor printer;
    func1 = printer;
    func1();

    typedef void(*SimpleFunction_t)();
    SimpleFunction_t functionPtr = PrintFunction;

    func1 = functionPtr;
    func1();

    return 0;
}