gpt4 book ai didi

c++ - 为什么我的模板特化不起作用?

转载 作者:搜寻专家 更新时间:2023-10-31 00:01:34 25 4
gpt4 key购买 nike

Code

#include<iostream>
using namespace std;

template<int N> void table(int i) { // <-- Line 4
table<N-1>(i);
cout << i << " * " << N << " = " << i * N << endl;
}

template<1> void table(int i) { // <-- Line 9
cout << i << " * " << 1 << " = " << i * 1 << endl;
}

int main() {

table<10> (5); // <-- Line 15
}

Expected Output

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Compilation

$ g++ templ.cpp 
templ.cpp:9: error: expected identifier before numeric constant
templ.cpp:9: error: expected `>' before numeric constant
templ.cpp:9: error: redefinition of 'template<int <anonymous> > void table(int)'
templ.cpp:4: error: 'template<int N> void table(int)' previously declared here
templ.cpp: In function 'int main()':
templ.cpp:15: error: call of overloaded 'table(int)' is ambiguous
templ.cpp:4: note: candidates are: void table(int) [with int N = 10]
templ.cpp:9: note: void table(int) [with int <anonymous> = 10]
$

为什么我的模板特化被编译器视为“重新定义”?

最佳答案

因为它应该是:

template<> void table<1>(int i)

代替

template<1> void table(int i) 

关于c++ - 为什么我的模板特化不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9768450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com