Почему моя специализация шаблона не работает? - PullRequest
2 голосов
/ 19 марта 2012

Код

#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 Ответ

7 голосов
/ 19 марта 2012

Потому что должно быть:

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

вместо

template<1> void table(int i) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...