Storing a list of arbitrary objects in C++

前端 未结 13 2036
野趣味
野趣味 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:15

    C++ does not support heterogenous containers.

    If you are not going to use boost the hack is to create a dummy class and have all the different classes derive from this dummy class. Create a container of your choice to hold dummy class objects and you are ready to go.

    class Dummy {
       virtual void whoami() = 0;
    };
    
    class Lizard : public Dummy {
       virtual void whoami() { std::cout << "I'm a lizard!\n"; }
    };
    
    
    class Transporter : public Dummy {
       virtual void whoami() { std::cout << "I'm Jason Statham!\n"; }
    };
    
    int main() {
       std::list hateList;
       hateList.insert(new Transporter());
       hateList.insert(new Lizard());
    
       std::for_each(hateList.begin(), hateList.end(), 
                     std::mem_fun(&Dummy::whoami));
       // yes, I'm leaking memory, but that's besides the point
    }
    

    If you are going to use boost you can try boost::any. Here is an example of using boost::any.

    You may find this excellent article by two leading C++ experts of interest.

    Now, boost::variant is another thing to look out for as j_random_hacker mentioned. So, here's a comparison to get a fair idea of what to use.

    With a boost::variant the code above would look something like this:

    class Lizard {
       void whoami() { std::cout << "I'm a lizard!\n"; }
    };
    
    class Transporter {
       void whoami() { std::cout << "I'm Jason Statham!\n"; }
    };
    
    int main() {
    
       std::vector< boost::variant > hateList;
    
       hateList.push_back(Lizard());
       hateList.push_back(Transporter());
    
       std::for_each(hateList.begin(), hateList.end(), std::mem_fun(&Dummy::whoami));
    }
    

提交回复
热议问题