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

3

17

I have a parameter pack given in a variadic class template 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? FirstEntityType should 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;
    
   // ...
};
Throw answered 8/8, 2017 at 21:44 Comment(0)
A
32

You could write:

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

Or you could use Boost.Mp11:

using FirstEntityType = mp_front<EntityContext>;
Avens answered 8/8, 2017 at 21:47 Comment(5)
Is this SFINAE friendly, and if so in what version of C++?Bibliotaph
@Yakk We're not in an immediate context, so doesn't matter?Avens
How is the first solution supposed to be used?Gratulate
@Gratulate What do you mean how? Just... as-is.Avens
Yeah, sorry, who know what the heck I was doing wrong.Gratulate
P
12

You may use

std::tuple_element<0, std::tuple<EntityTs...>>::type
Prejudge answered 8/8, 2017 at 21:48 Comment(0)
N
1

In c++-26 it will be possible to simply write

EntityTs...[0]

see https://en.cppreference.com/w/cpp/language/pack_indexing

Nichollenicholls answered 23/7 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.