0

I find myself constantly writing 4 different functions for the same use case.

Let's say I want to write a function 'contains' which tells me if the given set/map contains a value. Here would be my implementation:

template <class T, class V> bool contains(T S, V val) {
    return S.find(val) != S.end();
}

Now this function can be called by any template T. Can I restrict this to only apply to the above 4 stl classes? Or is there any other way to achieve my desired behaviour? I'm just making these functions for my own practice, so hacky solutions most welcome.

1 Answers1

0

You can write a dedicated type traits:

#include <set>
#include <map>
#include <type_traits>

template<typename T> struct
works_with_contains: ::std::false_type {};

template<typename Key, typename Compare, typename Allocator> struct
works_with_contains<::std::set<Key, Compare, Allocator>>: ::std::true_type {};

template <class T, class V> bool contains(T S, V val) {
    static_assert(works_with_contains<T>::value);
    return S.find(val) != S.end();
}
user7860670
  • 35,849
  • 4
  • 58
  • 84