C++ wrapper around any collection type using templates

  • A+
Category:Languages

Extremely new to c++ however have a question regarding templates

Suppose I have a simple template class as defined below:

template<typename Collection> class MySack { private:     Collection c;  public:     typedef typename Collection::value_type value_type;      void add(const value_type& value) {         c.push_back(value);     } }; 

The aim of the class being to accept any type of collection, and allow a user to insert the correct type of value for the specified typename Collection.

The obvious problem is that this is only going to work for types which have a push_back method defined, which means it would work with list however not with set.

I started reading about template specialization to see if that'd be any help, however I don't think this would provide a solution as the type contained within the set would have to be known.

How would this problem be approached in c++?


You can use std::experimental::is_detected and if constexpr to make it work:

template<class C, class V> using has_push_back_impl = decltype(std::declval<C>().push_back(std::declval<V>()));  template<class C, class V> constexpr bool has_push_back = std::experimental::is_detected_v<has_push_back_impl, C, V>;  template<typename Collection> class MySack { private:     Collection c;  public:     typedef typename Collection::value_type value_type;      void add(const value_type& value) {         if constexpr (has_push_back<Collection, value_type>) {             std::cout << "push_back./n";             c.push_back(value);         } else {             std::cout << "insert./n";             c.insert(value);         }     } };  int main() {     MySack<std::set<int>> f;     f.add(23);      MySack<std::vector<int>> g;     g.add(23); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: