空参数包的模板专业化
|
我有一个可变参数模板函数,该函数自行调用以确定列表中的最大数字(由模板化参数构成)。我正在尝试对参数包为空的情况进行专门化处理,以便仅返回列表顶部的数字,但是我不知道该怎么做。我刚刚熟悉了可变参数模板和模板专业化,但这是我到目前为止的内容:
#include <string>
#include <iostream>
using namespace std;
template <int N, int... N2>
int tmax() {
return N > tmax<N2...>() ? N : tmax<N2...>();
}
template <int N>
int tmax() {
return N;
}
int main() {
cout << tmax<32, 43, 54, 12, 23, 34>();
}
但是,这会产生以下错误:
test.cpp: In function ‘int tmax() [with int N = 34, int ...N2 = {}]’:
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 23, int ...N2 = {34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 12, int ...N2 = {23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 54, int ...N2 = {12, 23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 43, int ...N2 = {54, 12, 23, 34}]’
test.cpp:9:45: instantiated from ‘int tmax() [with int N = 32, int ...N2 = {43, 54, 12, 23, 34}]’
test.cpp:18:39: instantiated from here
test.cpp:9:45: error: no matching function for call to ‘tmax()’
test.cpp:9:45: error: no matching function for call to ‘tmax()’
我也尝试过这样做,只是看它是否可以工作(尽管它会随机将数字0引入列表,以便它永远不会返回小于0的数字):
template <int N, int... N2>
int tmax() {
return N > tmax<N2...>() ? N : tmax<N2...>();
}
template <>
int tmax<>() {
return 0;
}
但是,除了上面提到的错误之外,我还收到此错误:
error: template-id ‘tmax<>’ for ‘int tmax()’ does not match any template declaration
那么我应该怎么做才能使它正常工作呢?
我正在使用带有-std=c++0x
标志的g ++ 4.5.2。
没有找到相关结果
已邀请:
3 个回复
闪票仇门韧
54
联海
更新:根据ildjarn的建议,以下是较不冗长的版本:
系漏