c++c++11variadic-templates

variadic template pack within decltype


I may write as

template< class T0> struct Last0
{  
  using type = decltype(T0{}); // OK compiles. `type = T0`
};


template< class T0, class T1> struct Last1
{
    using type = decltype(T0{}, T1{}); // OK, compiles. `type = T1`
};

template< class T0, class T1, class T2> struct Last3{
   using type = decltype(T0{}, T1{}, T2{}); // Ok, compiles. `type = T2`
};

But, when I use variadic templates, it's not compiled:

template< class ... T> struct Last{
   using type = decltype(T{} ... ); //<--- Error !!!
};

What's problem?


Solution

  • There is a taxative list of language constructs where pack expansion can happen (C++11, 14.5.3§4). With the exception of sizeof..., it's always in constructs where the comma , is a grammatical separator of a list, and not an operator. An expression cannot be a pack expansion.

    To get the last type in a pack, you can do this:

    template <class Head, class... Tail>
    struct Last {
      typedef typename Last<Tail...>::Type Type;
    };
    
    template <class Head>
    struct Last<Head> {
      typedef Head Type;
    };