Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active August 29, 2015 14:07
Show Gist options
  • Save dgodfrey206/44d2fe81c462db6a0ef7 to your computer and use it in GitHub Desktop.
Save dgodfrey206/44d2fe81c462db6a0ef7 to your computer and use it in GitHub Desktop.
The third improved version of has_type. This version exhibits behavior equivalent to short circuiting with no recursion whatsoever.
#include <type_traits>
#include <tuple>
namespace detail
{
template <typename value, typename tuple>
struct has_type;
template <typename value, typename... xs>
struct has_type<value, std::tuple<xs...>>
{
private:
struct null;
static std::false_type
check(std::conditional_t<std::is_same<xs, value>::value, null, xs>...);
static std::true_type
check(...);
public:
using type = decltype(check(std::declval<xs>()...));
};
}
template <typename value, typename tuple>
using has_type_t = typename detail::has_type<value, std::decay_t<tuple>>::type;
template <typename value, typename tuple>
constexpr auto has_type(tuple&&) -> has_type_t<value, tuple>
{
return {};
}
int main()
{
constexpr std::tuple<bool, double, int, short> t{true, 3.14, 10, 12};
static_assert(has_type<int>(t), "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment