I have made a simple program that tests if the given element exists in any STL container. The program tests if the container has a find
member function. It will use it if it does. Otherwise, it will call the STL find
function instead. I would like to know how I can improve it further?
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
#include <vector>
#include <array>
#include <type_traits>
template <typename C> decltype(std::declval<C>().find(0), std::true_type{}) test(int);
template <typename C> std::false_type test(...);
template <typename C> using has_find = decltype(test<C>(0));
template <bool B, typename T, typename F>
std::enable_if_t<std::integral_constant<bool, B>::value, T>
conditional(T&& t, F&&)
{
return std::forward<T>(t);
}
template <bool B, typename T, typename F>
std::enable_if_t<!std::integral_constant<bool, B>::value, F>
conditional(T&&, F&& f)
{
return std::forward<F>(f);
}
template <typename C, typename T>
auto contains(const C& container, const T& key)
{
static auto first = [] (auto&& c, auto&& k)
{
return c.end() != c.find(k);
};
static auto second = [] (auto&& c, auto&& k)
{
return c.end() != std::find(c.begin(), c.end(), k);
};
auto op = conditional<has_find<C>::value>(first, second);
return op(container, key);
}
int main()
{
std::cout << std::boolalpha;
std::array<int, 3> a = {{ 1, 2, 3 }};
std::cout << contains(a, 0) << "\n";
std::cout << contains(a, 1) << "\n\n";
std::vector<int> v = { 1, 2, 3 };
std::cout << contains(v, 0) << "\n";
std::cout << contains(v, 1) << "\n\n";
std::set<int> s = { 1, 2, 3 };
std::cout << contains(s, 0) << "\n";
std::cout << contains(s, 1) << "\n\n";
std::map<int, int> m = { { 1, 1}, { 2, 2}, { 3, 3} };
std::cout << contains(m, 0) << "\n";
std::cout << contains(m, 1) << "\n";
}
contains()
algorithm forstd::vector
\$\endgroup\$