Search code examples
c++setpolymorphismstdmultiset

polymorphism between set and multiset in c++


Is there a way using polymorphism to have a generic for set and multiset? as follows.

Note: but only for sets, (set, multiset)

template<typename T>
void foo(parent_set<T> &s) {
    // do something
}
// main
set<int> s1 = {1, 2, 3, 4, 5};
foo(s1);
multiset<int> s2 = {1, 2, 2, 2, 2, 3};
foo(s2); 

Solution

  • Well, why don't you make the whole container your template parameter?

    template <class SetType>
    void foo( SetType&  s)
    {
        using T = typename SetType :: value_type;
        enter code here
        ....
    }
    

    The restriction for the parameter to only be a set or multiset, as is usually done with templates, is enforced by the usage of the template parameter as a set. E.g. you call insert with a single parameter, and therefore you cannot pass a vector. If there is a third, unknown, container that has all the required interface, maybe it makes sense to allow it as well?