Storing a list of arbitrary objects in C++

前端 未结 13 2017
野趣味
野趣味 2021-02-06 08:29

In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type.
For e

13条回答
  •  醉梦人生
    2021-02-06 09:08

    Your example using Boost.Variant and a visitor:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    using namespace boost;
    
    typedef variant object;
    
    struct vis : public static_visitor<>
    {
        void operator() (string s) const { /* do string stuff */ }
        void operator() (int i) const { /* do int stuff */ }
        void operator() (bool b) const { /* do bool stuff */ }      
    };
    
    int main() 
    {
        list List;
    
        List.push_back("Hello World!");
        List.push_back(7);
        List.push_back(true);
    
        BOOST_FOREACH (object& o, List) {
            apply_visitor(vis(), o);
        }
    
        return 0;
    }
    
    
    

    One good thing about using this technique is that if, later on, you add another type to the variant and you forget to modify a visitor to include that type, it will not compile. You have to support every possible case. Whereas, if you use a switch or cascading if statements, it's easy to forget to make the change everywhere and introduce a bug.

    提交回复
    热议问题