空参数包的模板专门化 [英] Template specialization for an empty parameter pack

查看:157
本文介绍了空参数包的模板专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a variadic template function which calls itself to determine the largest number in a list (constituted by the templatized arguments). I am trying to make a specialization for when the parameter pack is empty so I can just return the number at the front of the list, but I don't know how to do that. I am just becoming familiar with variadic templates and template specialization, but this is what I have so far:

#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>();
}
However, this produces the following error:

只是看看它是否会工作(虽然它随机地将数字0引入列表,以便它不能返回一个小于0的数字):

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()’

I have also tried this, just to see if it would work (although it introduces the number 0 to the list randomly so that it can't ever return a number less than 0):

但是,另外 ,我得到这个错误:

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

However, in addition to the errors mentioned above, I get this error:

那么我该怎么做才能使这个工作?

error: template-id ‘tmax<>’ for ‘int tmax()’ does not match any template declaration

我使用g ++ 4.5.2和 -std = c ++ 0x 标志。

So what should I do to get this working?

推荐答案

我发现两个错误使用 clang


  1. 将重载作为单独的int。

I see two mistakes using clang.



Make things unambiguous for lists of length 1. Recall that variadic lists can have zero size and when they do, it seems to me you have an ambiguity.

#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

这篇关于空参数包的模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆