Note:
My concern here is about compilation speeds.
I assume that recursive type traits are typically slower than the alternatives (when possible). If I'm wrong about this then please let me know.
We can access the types at the front of a variadic list without recursion, like so:
#include <iostream>
#include <type_traits>
template <typename T>
struct this_type
{
using type = T;
};
template <typename T1, typename ...>
struct front : this_type<T1> {};
template <typename ... Ts>
using front_t = typename front<Ts...>::type;
template <typename ... Ts>
void Foo ()
{
std::cout << std::is_same_v<front_t<Ts...>, int> << std::endl;
}
int main ()
{
Foo<int, char, bool>();
}
However, I can't think of a generic way to access the back type without recursion. Intuitively I'd want to do something like this:
template <typename ...>
struct pack;
template <typename ...>
struct back;
template <typename Tn, typename ... Ts>
struct back <pack<Ts..., Tn>> : this_type<Tn> {};
template <typename ... Ts>
using back_t = typename back<pack<Ts...>>::type;
... but the variadic template needs to be the last argument in the specialisation.
We can use a bit of code bloat to manage accessing elements up to a certain amount. eg, 3:
template <typename ...>
struct back;
template <typename T1>
struct back <T1> : this_type<T1> {};
template <typename T1, typename T2>
struct back <T1, T2> : this_type<T2> {};
template <typename T1, typename T2, typename T3>
struct back <T1, T2, T3> : this_type<T3> {};
template <typename ... Ts>
using back_t = typename back<Ts...>::type;
template <typename ... Ts>
void Foo ()
{
std::cout << std::is_same_v<back_t<Ts...>, bool> << std::endl;
}
int main ()
{
Foo<int, char, bool>();
}
...But is there a way to do it generically without recursion?
Motivation:
Often we can change the way that we solve a problem so that we access from near the front of a variadic list, but sometimes it's unavoidable to access from the back. I don't want to create useless work for the compiler if there's some language feature that I'm not taking advantage of.