空参数包的模板特化

Set*_*gie 14 c++ templates template-specialization variadic-templates c++11

我有一个可变参数模板函数,它调用自己来确定列表中的最大数字(由模板化参数构成).我试图在参数包为空时进行专门化,这样我就可以返回列表前面的数字,但我不知道该怎么做.我只是熟悉可变参数模板和模板专业化,但这是我到目前为止所拥有的:

#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>();
}
Run Code Online (Sandbox Code Playgroud)

但是,这会产生以下错误:

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()’
Run Code Online (Sandbox Code Playgroud)

我也试过这个,只是为了看看它是否会起作用(虽然它会随机地将数字0引入列表中,以便它不能返回小于0的数字):

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

template <>
int tmax<>() {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,除了上面提到的错误,我收到此错误:

error: template-id ‘tmax<>’ for ‘int tmax()’ does not match any template declaration
Run Code Online (Sandbox Code Playgroud)

那么我该怎么办呢?

我正在使用带有-std=c++0x标志的g ++ 4.5.2 .

How*_*ant 26

我看到使用clang的两个错误.

  1. 将重载首先放在单个int中.

  2. 使长度为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>();
}
Run Code Online (Sandbox Code Playgroud)

54


Ker*_* SB 5

就个人而言,我更喜欢在函数中使用静态类成员来做这种事情:

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;
}
Run Code Online (Sandbox Code Playgroud)

更新:使用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)> { };
Run Code Online (Sandbox Code Playgroud)