本文介绍了decltype中的可变参数模板包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以写为
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 !!!
};
有什么问题?
推荐答案
有一个可以进行包扩展的语言结构的征税列表(C ++ 11,14.5.3§4)。除了 sizeof ...
,它总是在结构中,其中逗号,
是列表的语法分隔符,而不是操作者。
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;
};
这篇关于decltype中的可变参数模板包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!