0

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); 
  • 2
    Since you are using a template anyway, you can just template for the entire container type. – François Andrieux May 19 '21 at 17:26
  • 2
    You cannot have polymorphic behavior between types that are not related (i.e. have no inheritance relationship). Instead you can just rely on duck-typing using templates in this case. – Cory Kramer May 19 '21 at 17:26

1 Answers1

5

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?

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434