How do I get the index of a type that matches some predicate?
I have a variation list of types and I want to find the index of the first type with the base of the type Base
. If he cannot find it, he must return it -1
. This is how I would like to do it:
typedef std::tuple<A, B, C> Tuple;
int idx = find_if<std::is_base_of, Base, Tuple>::value;
Where std::is_base_of
is the predicate Base
is its argument, and the tuple are the elements to test.
+3
source to share
1 answer
What about
constexpr std::size_t npos = -1;
template <template <class T> class, typename, std::size_t pos = 0>
struct find_if;
template <template <class T> class Pred, typename T, std::size_t pos, typename... tail>
struct find_if<Pred, std::tuple<T, tail...>, pos> :
std::conditional<Pred<T>::value,
std::integral_constant<std::size_t, pos>,
find_if<Pred, std::tuple<tail...>, pos+1>>::type {};
template <template <class T> class Pred>
struct find_if<Pred, std::tuple<>> : std::integral_constant<std::size_t, npos> {};
template <template <class, class> class T, class U>
struct bind
{
template <class X>
using first = T<U, X>;
template <class X>
using second = T<X, U>;
};
Use this:
find_if<bind<std::is_base_of, Base>::first, Tuple>::value
Demo .
+4
source to share