Skip to content

Instantly share code, notes, and snippets.

@oliora
Last active February 25, 2016 12:34
Show Gist options
  • Save oliora/b8207b4a74a6bb868ef4 to your computer and use it in GitHub Desktop.
Save oliora/b8207b4a74a6bb868ef4 to your computer and use it in GitHub Desktop.
#include <type_traits>
#include <utility>
#include <algorithm>
namespace has_own_find_impl__ {
struct two__ { char c__[2]; };
template <class T> static two__ test__(...);
template <class T> static char test__(decltype(std::declval<T>().find(std::declval<typename T::key_type>()))* = 0);
}
namespace {
template <class T>
struct has_own_find
: public std::integral_constant<bool, sizeof(has_own_find_impl__::test__<T>(nullptr)) == sizeof(char)>
{};
template<class Cont, class T>
auto do_find(const Cont& c, T&& value) -> typename std::enable_if<!has_own_find<Cont>::value, typename Cont::const_iterator>::type
{
using std::begin;
using std::end;
return std::find(begin(c), end(c), std::forward<T>(value));
}
template<class Cont, class T>
auto do_find(const Cont& c, T&& value) -> typename std::enable_if<has_own_find<Cont>::value, typename Cont::const_iterator>::type
{
return c.find(std::forward<T>(value));
}
}
//////////////////////////////////////////////////////////////
// Usage example:
template<class Cont>
void do_it()
{
const Cont c{1,2,3,4,5};
auto const it = do_find(c, 2);
assert(it != c.end());
std::cout << *it << "\n";
}
do_it<std::vector<int>>();
do_it<std::set<int>>();
//////////////////////////////////////////////////////////////
@pudov
Copy link

pudov commented Feb 22, 2016

why do u use forward()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment