I know how to select first parameter of variadic template:
template< class...Args> struct select_first; template< class A, class ...Args> struct select_first<A,Args...>{ using type = A;};
It's a very simple. However, select_last is not similar:
template< class ...Args> struct select_last; template< class A> struct select_last<A> { using type = A; }; template< class A, class Args...> struct select_last<A,Args...>{ using type = typename select_last<Args...>::type; };
This solution needed deep recursive template instantinations. I try to solve this with as:
template< class A, class Args...> struct select_last< Args ... , A>{ using type = A; }; // but it's not compiled.
Q: exist more effective way to selecting last parameter of variadic templates?
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
A function parameter pack is a function parameter that accepts zero or more function arguments. A template with at least one parameter pack is called a variadic template.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
With C++17, the cleanest way is
template<typename T> struct tag { using type = T; }; template<typename... Ts> struct select_last { // Use a fold-expression to fold the comma operator over the parameter pack. using type = typename decltype((tag<Ts>{}, ...))::type; };
with O(1) instantiation depth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With