language: C++ 4.7.2 (gcc-4.7.2)
date: 1023 days 23 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
    #include <boost/variant.hpp>
    #include <boost/function.hpp>
    #include <boost/foreach.hpp>
    #include <map>
    #include <string>
    #include <iostream>
    
    typedef boost::variant<boost::function<int()>,
                           boost::function<float()>,
                           boost::function<double()> > Callback;
    typedef std::map<std::string, Callback> CallbackType;
    
    CallbackType mCallbacks;
    
    void Foo(const std::string& name, const Callback& f) {
        mCallbacks[name] = f;
    }
    
    //------------------------------------------------------------------------------
    
    float f() { 
        std::cout << "f called" << std::endl;
        return 4;
    }
    
    int g() {
        std::cout << "g called" << std::endl;
        return 5;
    }
    
    double h() {
        std::cout << "h called" << std::endl;
        return 4;
    }
    
    //------------------------------------------------------------------------------
    
    struct call_visitor : public boost::static_visitor<> {
        template <typename T>
        void operator() (const T& operand) const {
                operand();
        }
    };
    
    
    int main () {
        Foo("f", boost::function<float()>( f ));
        Foo("g", boost::function<int()>( g ));
        Foo("h", boost::function<double()>( h ));
                
        BOOST_FOREACH(CallbackType::value_type &row, mCallbacks) {
                boost::apply_visitor(call_visitor(), row.second);
        }
    
        return 0;
    }