我有一个可变参数模板函数,它调用自身来确定列表中的最大数字(由模板化参数构成)。我正在尝试对参数包为空时进行专门化,因此我可以只返回列表前面的数字,但我不知道该怎么做。我刚刚熟悉可变参数模板和模板专业化,但这是我目前所拥有的:
#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。