为什么我的模板专业化不起作用?

时间:2012-03-19 10:21:22

标签: c++ templates

  

代码

#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
}
  

预期输出

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
  

汇编

$ 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]
$

为什么我的模板专业化被编译器视为'重新定义'?

1 个答案:

答案 0 :(得分:7)

因为它应该是:

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

而不是

template<1> void table(int i)