简体   繁体   中英

How do I use a base class as a placeholder for derived classes in C++?

I'm looping through some code to populate some objects. I've spent too long trying to simplify the loop but I got stuck on using a base class as a placeholder for derived classes. I feel like it should be possible, but I can't make it work.

I'm running through a map, looking for specific strings in the value. If I find one such string, I strip it down and store the data it contains in an object. Depending on the string, I need the information stored in different subclasses (probably 5-7 subclasses). I feel like I can shorten it further without losing readability, by using the parent object as the temporary object and defining it only once inside the for-loop, but I can't figure out how. The.push_back() function won't work if I do all_object_As.push_back(parent_object).

The store_data() function is only defined in the parent class.

std::vector<Derived_object_A> all_object_As;
std::vector<Derived_object_B> all_object_Bs;    

for (auto element : some_map)
{
    std::vector<string> data_buffer = separate_data(get_data(element.second));

    if (element.second.find("SOMETEXT") != string::npos)
    {
        Derived_object_A object;
        object.store_data(data_buffer);

        all_object_As.push_back(object);
    }

    if (element.second.find("SOMEOTHERTEXT") != string::npos)
    {
        Derived_object_b object;
        object.store_data(data_buffer);

        all_object_Bs.push_back(object);
    }
}

The natural approach would be to replace:

std::vector<Derived_object_A> all_object_As;
std::vector<Derived_object_B> all_object_Bs; 

with

std::vector<Base_object&> all_objects;

but you can't have a vector of references. So, that leaves you with various approaches:

std::vector<Base_object*> all_objects_ptr; // but then you need to manage ownership and lifetimes
std::vector<std::shared_ptr<Base_object>> all_objects_shared_ptr;

There's probably a way with reference_wrapper too.

What's best for you is probably opinion-based and would require seeing more code, anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM