Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through a container of types different based on template parameter to call same method

(I’m restricted to C++14 for now but if C++17 or 20 can allow this, please do say)

I have a class/struct containing different types:

struct Aggregation
{
    Something<P> _p;
    Something<S> _s;
    Something<T> _t;
    // There's a lot more
};

Although each type is simply a different templated parameter of Something:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template<class T>
struct Something
{
    std::string export(){return "some stuff";}
};

I want to store these types in a container.

This is because I need to loop across all objects and call the same method:

std::string str;
for(auto& obj : some_container)
{
    str += obj.export() + ",";
}

Is this possible?

>Solution :

Is this possible?

Yes! Create a common base, with the common functionality.

struct SomethingBase
{
    virtual std::string export() = 0;
};

Every instantiation of Something can inherit from that common base.

template<class T>
struct Something : SomethingBase
{
    std::string export() override {return "some stuff";}
};

You may now create any container of pointers to the common base. They may refer to any instantiation of Something.

// If the container owns the objects:
std::vector< std::unique_ptr<SomethingBase> > some_container;

// or

// If the objects are owned elsewhere:
std::vector< SomethingBase* > some_container;

Your proposed code (adjusted for pointers) will now work.

std::string str;
for(auto const& obj : some_container)
{
    str += obj->export() + ",";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading