在C ++ 11中处理零参数可变参数模板
考虑以下人工示例:
template <typename T, typename... Args>
struct A {
typedef T Type;
};
使用带有一个或多个参数的 A
可以正常工作而将其与零参数一起使用时按预期会失败:
Using A
with 1 or more arguments works while using it with zero arguments fails as expected:
错误:模板参数的数量错误(0,应为1或更多)
error: wrong number of template arguments (0, should be 1 or more)
是否有可能使 A
处理零个定义 A :: Type 到 int
如果没有参数,则返回第一个模板参数?
Is it possible to make A
handle the case of zero template arguments defining A::Type
to int
if there are no arguments and to the first template argument if there are?
首先将主模板定义为最常见的情况—其中还包含零参数:
First define the primary template as the most general case — which also includes zero argument:
template <typename... Args> //general : 0 or more
struct A { using Type = int; }
然后 partially 将其专门用于 1个或更多参数为:
Then partially specialize it for 1 or more parameters as:
template <typename T, typename... Args> //special : 1 or more
struct A<T,Args...> { using Type = T; }
一旦拥有了这个专业化,主模板将仅用于零参数 !
Once you have this specialization, the primary template would be used for zero-argument only!
请注意,数学上 1或更多是 0或更多的特殊情况—后者是更一般的情况(不是相反)。
Note that mathematically 1 or more is a special case of 0 or more — the latter is a more general case (not the other way round).