【发布时间】:2012-01-14 04:24:03
【问题描述】:
我正在尝试编写一个可变参数模板来查找任意数量的最大值(这只是为了练习可变参数模板)。
但是,我有点碰壁,无法理解为什么我当前的尝试根本不起作用,并且在编译时失败并出现错误:
prog.cpp: In function 'A myMax(A, A, Args ...) [with A = int, Args = {}]':
prog.cpp:7:35: instantiated from 'A myMax(A, A, Args ...) [with A = int, Args = {int}]'
prog.cpp:22:26: instantiated from here
prog.cpp:7:35: error: no matching function for call to 'myMax(int)'
我的代码如下:
#include <iostream>
template <typename A, typename ... Args>
A myMax(A a, A b, Args ... args)
{
return myMax(myMax(a,b),args...);
}
template <typename A>
A myMax(A a,A b)
{
if (a>b)
return a;
else
return b;
}
int main()
{
std::cout<<myMax(1,5,2);
}
谁能告诉我如何修复我的可变参数模板?
【问题讨论】:
-
好的,但是一旦你完成了学习,请返回并使用
std::max:-)
标签: c++ templates c++11 variadic-functions