user997112
user997112

Reputation: 30635

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:

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?

Upvotes: 0

Views: 163

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63912

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() + ",";
}

Upvotes: 3

Related Questions