effective way to select last parameter of variadic template

后端 未结 8 913
温柔的废话
温柔的废话 2020-12-01 12:37

I know how to select first parameter of variadic template:

template< class...Args> struct select_first;
template< class A, class ...Args> struct          


        
8条回答
  •  甜味超标
    2020-12-01 13:33

    If you are willing to strip references blindly from your type list (which is quite often the case: either you know they are references, or you don't care), you can do this with little machinery outside of std. Basically stuff the data into a tuple or tie, then use std::get( tuple or tie ) to extract the last element.

    You can do this in a pure-type context using std::declval< std::tuple >() and decltype, and possibly std::remove_reference.

    As an example, suppose you have a variardic set of arguments, and you want to return the last argument ignoring the rest:

    #define RETURNS(x) ->decltype(x) { return (x); }
    
    template
    auto get_last( Args&&... args )
      RETURNS( std::get< sizeof...(Args)-1 >( std::tie(std::forward(args)...) ) )
    

    we can then use this in another function:

    template
    void foo( Args&&... args ) {
      auto&& last = get_last(std::forward(args)...);
    }
    

提交回复
热议问题