Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the first type of a parameter pack in a one-liner?

I have a parameter pack given in a variadic template class and want to extract the first type.

Currently I do this, which works fine but is somehow cumbersome. Is it possible to do the same thing simpler? FirstEntityTypeshould be defined to have the type of the first type in EntityTs. Note, I want to keep the signature of the class template. I know that it would be possible to write template<typename FirstEntityType, typename... OtherEntityTypes>, it is however something that I don't want to do.

template<typename... EntityTs>
struct EntityContext
{
    template<typename T, typename ... Ts>
    struct K {
        using type = T;
    };

    using FirstEntityType = typename K<EntityTs...>::type;
    
   // ...
};
like image 786
dani Avatar asked Aug 08 '17 21:08

dani


People also ask

What is a parameter pack?

[edit] A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). 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.

How do you expand a parameter pack?

Parameter packs can only be expanded in a strictly-defined list of contexts, and operator , is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator , .

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.


2 Answers

You could write:

using FirstEntityType = std::tuple_element_t<0, std::tuple<EntityTs...>>;

Or you could use Boost.Mp11:

using FirstEntityType = mp_front<EntityContext>;
like image 50
Barry Avatar answered Oct 13 '22 12:10

Barry


You may use

std::tuple_element<0, std::tuple<EntityTs...>>::type
like image 25
Jarod42 Avatar answered Oct 13 '22 11:10

Jarod42