I wrote the following template function, which checks whether an arbitary container contains a specific element:
template<template<class, class...> class container_t, class item_t, class... rest_t>
bool contains(const container_t<item_t, rest_t...> &_container, const item_t &_item) {
for(const item_t &otherItem : _container) {
if(otherItem == _item) { return true; }
}
return false;
}
This works well for most containers. However for all kinds of sets (and maps) it is sub optimal since there we could use:
template<template<class, class...> class set_t, class item_t, class... rest_t>
bool contains(const set_t<item_t, rest_t...> &_set, const item_t &_item) {
return _set.count(_item) > 0;
}
Obviously we can't use both templates simultaneously because of ambiguity. Now I am looking for a way to use std::enable_if
to enable the to first template if container_t
does not provide a count
member function and the second template if it does. However I can't figure out how to check for a specif member function (using C++11).
BOOST_TTI_HAS_MEMBER_FUNCTION
macro – Nanetefind
form you want to use to make it explicitly clear when you're doing a linear search and when you're using a more efficient mechanism. As a side note if you really do want to do this, definitely usefind
instead ofcount
, it's just avoiding premature pessimization. – Dietzstd::find
also uses different algorithms depending on whether or not we have an ordered container, doesn't it? At least en.cppreference.com/w/cpp/algorithm/find writes that the complexity is at most linear, i.e. can be less than linear for suitable containers. However correct me if I am wrong. – Translative