首页 > 解决方案 > 使用可变参数函数模板,我们可以设计一个至少可以用 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) ;
}

如果这是可能的,有人可以告诉我怎么做吗?

标签: c++variadic-templates

解决方案


确保返回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...);
}

推荐阅读