Lazer
Lazer

Reputation: 94800

Why does my template specialization not work?

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

Why is my template specialization being considered as a 'redefinition' by the compiler?

Upvotes: 2

Views: 486

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

Because it should be:

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

instead of

template<1> void table(int i) 

Upvotes: 7

Related Questions