空参数包的模板专业化

| 我有一个可变参数模板函数,该函数自行调用以确定列表中的最大数字(由模板化参数构成)。我正在尝试对参数包为空的情况进行专门化处理,以便仅返回列表顶部的数字,但是我不知道该怎么做。我刚刚熟悉了可变参数模板和模板专业化,但这是我到目前为止的内容:
#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。     
已邀请:
        我看到使用c的两个错误。 将重载放在第一个int位置。 使长度为1的列表毫无歧义。回想一下,可变参数列表的大小可以为零,而当它们做到这一点时,在我看来,您就有歧义。 这将为我编译并正确运行:
#include <iostream>

using namespace std;

template <int N>
int tmax() {
    return N;
}

template <int N, int N1, int... N2>
int tmax() {
    return N > tmax<N1, N2...>() ? N : tmax<N1, N2...>();
}

int main() {
    cout << tmax<32, 43, 54, 12, 23, 34>();
}
54     
        就个人而言,对于此类事情,我更喜欢使用静态类成员而不是函数:
template <int... N> struct max;
template <int N, int... M> struct max<N, M...> {
  static const int value = max<N, max<M...>::value>::value;
};    
template <int N, int M> struct max<N, M> {
  static const int value = N > M ? N : M;
};

int main()
{
  return max<1,2,3>::value;
}
更新:根据ildjarn的建议,以下是较不冗长的版本:
#include <type_traits>
template <int... N> struct max;
template <int N, int... M> struct max<N, M...>
  : std::integral_constant<int, max<N, max<M...>::value>::value> { };
template <int N, int M> struct max<N, M>
  : std::integral_constant<int, (N > M ? N : M)> { };
    
        由于您不能部分专门化功能,因此需要包装功能:
template<int Head, int... Tail>
struct Tmax{
  static int do(){
    return Head > Tmax<Tail...>::do() ? Head : Tmax<Tail...>::do();
  }
};

template<int N>
struct Tmax<N>{
  static int do(){
    return N;
  }
};

template<int... Numbers>
int tmax(){
  return Tmax<Numbers...>::do();
}
    

要回复问题请先登录注册