Storing a list of arbitrary objects in C++

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

    boost::variant is similar to dirkgently's suggestion of boost::any, but supports the Visitor pattern, meaning it's easier to add type-specific code later. Also, it allocates values on the stack rather than using dynamic allocation, leading to slightly more efficient code.

    EDIT: As litb points out in the comments, using variant instead of any means you can only hold values from one of a prespecified list of types. This is often a strength, though it might be a weakness in the asker's case.

    Here is an example (not using the Visitor pattern though):

    #include 
    #include 
    #include 
    
    using namespace std;
    using namespace boost;
    
    ...
    
    vector > v;
    
    for (int i = 0; i < v.size(); ++i) {
        if (int* pi = get(v[i])) {
            // Do stuff with *pi
        } else if (string* si = get(v[i])) {
            // Do stuff with *si
        } else if (bool* bi = get(v[i])) {
            // Do stuff with *bi
        }
    }
    

    (And yes, you should technically use vector::size_type instead of int for i's type, and you should technically use vector::iterator instead anyway, but I'm trying to keep it simple.)

提交回复
热议问题