c++ - 使用可变参数函数模板,我们可以设计一个至少可以用 2 个参数调用的函数吗?
问题描述
我刚刚开始了解可变参数函数模板。是否可以定义用 2 个或更多参数编写通用案例(处理递归)?也就是说,我想知道我可以写如下内容:
template <class T>
void min(T val1, T val2) { return val1>val2 ? val2 : val1 ; }
template <class T, class... Others>
void min(T a1, T a2, Others ... others) {
// implementation
T a = a1 > a2 ? a2 : a1 ;
// min(a, first-element-in-others, all-elems-in-others-except-first) ;
}
如果这是可能的,有人可以告诉我怎么做吗?
解决方案
确保返回T
并且不写using namespace std
,否则你会与标准库函数发生冲突,min
.
#include <algorithm>
template <class T>
T min (T a)
{
return a;
}
template <class T, class... Ts>
T min (T a1, T a2, Ts ... as)
{
return min(std::min(a1, a2), as...);
}
推荐阅读
- typescript - 在打字稿中没有正确检查条件/三元结果?
- c# - 在 ASP.Net 中使用 Web 服务,不工作
- javascript - 将参数添加到函数以仅在值与数组中的名称匹配时执行
- aws-lambda - 将 SQS Lambda 批处理拆分为部分成功/部分失败
- php - MySQL 查询在晚上没有返回结果,也没有抛出错误
- html - 如何将'*'函数属性赋予html中的另一个div
- node.js - Knex:如何在 ARM 上修复“无法读取未定义的属性‘原型’”以进行初始设置
- ruby-on-rails - 在 Rails 控制台中使用辅助方法时确定 Rails 中标签方法的源位置
- css - 如何在 Sass 中错开多个动画延迟?
- security - 安全远程调试 JBoss