Home > Net >  C 20 How to get the last element of a parameter pack of std::size_t
C 20 How to get the last element of a parameter pack of std::size_t

Time:11-04

I've seen many answers online such as this one, but they do not seem to work when the parameter pack is of std::size_t.

template <typename ...Ts>
struct select_last
{
    using type = typename decltype((std::type_identity<Ts>{}, ...))::type;
};

template<std::size_t... N>
class Example {
private:
    using type = select_last<int, double>::type; // works
    using size_t_type = select_last<size_t... N>::type; // doesn't work
};

How can I get the last element of a parameter pack of type std::size_t?

CodePudding user response:

The template<std::size_t... N> is based on a non-type template parameter, so you cannot extract the type (or more precisely, there is no sense in trying to extract the type - I can just tell you it is std::size_t!), you may however extract the value, into a static constexpr.

Here is the proposed code:

template<std::size_t... N>
struct Last {
    static constexpr std::size_t val = (N, ...); // take the last
};

int main() {
    std::cout << Last<1, 2, 3, 99>::val; // 99
}

If you want, you can actually have it work for any type:

template<auto... N>
struct Last {
    static constexpr auto val = (N, ...); // take the last
};
  • Related