Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement template parameter inside a fold expression

Tags:

c++

templates

Consider the following code:

template<typename...>
struct C
{ /* ... */ };

template<typename T, unsigned N>
struct B
{
    using type = /* ... */;
};

template<size_t N, typename... Ts>
struct A
{
    using type = C<typename B<Ts, N-->::type...>; // decrement N sizeof...(Ts) times
};

So for example

typename A<5, int, long, void>::type

expands to

C<typename B<int, 5>::type, typename B<long, 4>::type, typename B<void, 3>::type>

Since N is a const value, this code does not compile. Is there any other way?

like image 432
user7769147 Avatar asked Dec 17 '22 14:12

user7769147


1 Answers

Subtract a std::index_sequence from N

namespace detail {
    template<size_t N, typename... Ts, size_t... Is>
    C<typename B<Ts, N - Is>::type...> A_impl(std::index_sequence<Is...>);
}

template<size_t N, typename... Ts>
struct A
{
    using type = decltype(detail::A_impl<N, Ts...>(std::index_sequence_for<Ts...>{}));
};
like image 148
Caleth Avatar answered Dec 20 '22 04:12

Caleth