Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

effective way to select last parameter of variadic template

Tags:

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?

like image 791
Khurshid Normuradov Avatar asked Sep 22 '13 09:09

Khurshid Normuradov


People also ask

Can we pass Nontype parameters to 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.

What is parameter pack in c++?

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.

What is Variadic template in C++?

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.

What are template parameters?

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.


1 Answers

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.

like image 182
Passer By Avatar answered Nov 06 '22 17:11

Passer By