获取可变模板参数的尾部

Take tail of variadic template parameters

鉴于此类型:

template<typename ...As>
struct Base {};

我需要实现一个功能

template<int i, typename ...As>
constexpr auto Tail() {
   static_assert(i < sizeof...(As), "index out of range");
   return ??;
}

其中 returns B 的实例使用索引 i 中类型参数列表的尾部。

例如,

Tail<0, int, float, double>() -> Base<int, float, double>
Tail<1, int, float, double>() -> Base<float, double>
Tail<2, int, float, double>() -> Base<double>
Tail<3, int, float, double>() -> fails with static assert

我知道如何获取索引 i 处的类型:

template <int64_t i, typename T, typename... Ts>
struct type_at
{
    static_assert(i < sizeof...(Ts) + 1, "index out of range");
    typedef typename type_at<i - 1, Ts...>::type type;
};

template <typename T, typename... Ts> struct type_at<0, T, Ts...> {
    typedef T type;
};

但我无法获得解决整个问题的工作版本。

对于Tail(为什么是函数?),做法可以和type_at差不多。您唯一需要更改的是递归的基本情况:

template <typename ... Ts>
struct types_from<0, Ts...> {
    using type = Base<Ts...>; // we don't like nasty typedef syntax
};

如果您不介意使用 C++17。连 static_assert 都不需要:

template<unsigned i, typename T, typename ...Ts>
constexpr auto Tail() {
    if constexpr (i == 0)
        return Base<T, Ts...>();
    else 
        return Tail<i - 1, Ts...>();
}


int main(){
    Base<int, double, int> a = Tail<0, int, double, int>();    
    Base<double, int> b = Tail<1, int, double, int>();
    Base<int> c = Tail<2, int, double, int>();
    auto d = Tail<3, int, double, int>();
}

顺便说一句,将 int 更改为 unsigned 以避免负数(几乎)无限递归的可能性。

而现在,为了一些完全不同的东西...

为了好玩,我提出了一个 C++14 解决方案,它不使用递归,而是使用 std::tuple_cat() 的强大功能。

#include <tuple>
#include <type_traits>

template <typename...>
struct Base
 { };

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I <= J), bool> = true>
constexpr std::tuple<Base<A>> Tail_helper3 ();

template <std::size_t I, std::size_t J, typename A,
          std::enable_if_t<(I > J), bool> = true>
constexpr std::tuple<> Tail_helper3 ();

template <typename ... As>
constexpr Base<As...> Tail_helper2 (std::tuple<Base<As>...> const &);

template <std::size_t I, typename ... As, std::size_t ... Is>
constexpr auto Tail_helper1 (std::index_sequence<Is...> const &)
   -> decltype( Tail_helper2(std::tuple_cat(Tail_helper3<I, Is, As>()...)) );

template <std::size_t I, typename ... As>
constexpr auto Tail () 
   -> decltype( Tail_helper1<I, As...>(std::index_sequence_for<As...>{}) )
 {
   static_assert(I < sizeof...(As), "index out of range");

   return {};
 }

int main ()
 {
   static_assert( std::is_same_v<Base<int, double, int>,
                                 decltype(Tail<0u, int, double, int>())> );

   static_assert( std::is_same_v<Base<double, int>,
                                 decltype(Tail<1u, int, double, int>())> );

   static_assert( std::is_same_v<Base<int>,
                                 decltype(Tail<2u, int, double, int>())> );

   // Tail<3u, int, double, int>(); compilation error!
 }