2

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?

1
  • 1
    The type-based code doesn't work if any of those Ts cannot be default constructed. You should use std::declval<Ts>() instead. Commented Nov 4, 2022 at 5:34

1 Answer 1

3

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 }; 
Sign up to request clarification or add additional context in comments.

2 Comments

I would use something like constexpr std::array<size_t, sizeof...(N)> vals{N...}. It basically gives you the full control over the pack.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.