在C ++ 11中处理零参数可变参数模板 [英] Handling zero-argument variadic template in C++11

查看:75
本文介绍了在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 处理零个定义<$的模板参数的情况c $ c> 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).

这篇关于在C ++ 11中处理零参数可变参数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆