加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 空参数包的模板专门化

发布时间:2020-12-16 05:39:40 所属栏目:百科 来源:网络整理
导读:我有一个可变的模板函数,它调用自己来确定列表中最大的数字(由模板参数组成).当我的参数包为空时,我试图做一个专门化的工作,所以我可以在列表的前面返回数字,但是我不知道该怎么做.我只是熟悉可变模板和模板专业化,但这是我到目前为止: #include string#inc
我有一个可变的模板函数,它调用自己来确定列表中最大的数字(由模板参数组成).当我的参数包为空时,我试图做一个专门化的工作,所以我可以在列表的前面返回数字,但是我不知道该怎么做.我只是熟悉可变模板和模板专业化,但这是我到目前为止:
#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,34}]’
test.cpp:9:45:   instantiated from ‘int tmax() [with int N = 43,int ...N2 = {54,34}]’
test.cpp:9:45:   instantiated from ‘int tmax() [with int N = 32,int ...N2 = {43,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

那我该怎么办才能得到这个工作?

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

解决方法

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

>把重载放在一个单一的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,34>();
}

54

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读