variadic template pack within decltype

喜欢而已 提交于 2019-12-12 11:02:59

问题


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?


回答1:


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;
};



回答2:


You can only apply decltype to an expression, not to a pack. Packs are very special and basically always need to be expanded. You essentially have the same problem as not being able to store packs directly: using type = T... isn't allowed, either.

The standard solution is to store packs inside some "container template", typically tuple:

using T = std::tuple<decltype(T{})...>;


来源:https://stackoverflow.com/questions/19045579/variadic-template-pack-within-decltype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!