Twój kod nie jest szablonową specjalizacją, ale raczej niesformatowaną funkcją. Tam są pewne różnice. Operator bez matrycy() będzie mieć pierwszeństwo nad matrycy wersji (na dokładne dopasowanie, ale typ konwersji nie odbędzie się tam), ale nadal można zmusić funkcję matrycy na miano:
class Visitor
{
public: // corrected as pointed by stefanB, thanks
template <typename T>
void operator()(T data) {
std::cout << "generic template" << std::endl;
}
void operator()(bool data) {
std::cout << "regular member function" << std::endl;
}
};
template <> // Corrected: specialization is a new definition, not a declaration, thanks again stefanB
void Visitor::operator()(int data) {
std::cout << "specialization" << std::endl;
}
int main()
{
Visitor v;
v(5); // specialization
v(true); // regular member function
v.operator()<bool>(true); // generic template even if there is a non-templated overload
// operator() must be specified there (signature of the method) for the compiler to
// detect what part is a template. You cannot use <> right after a variable name
}
w twojej Kod nie ma wielkiej różnicy, ale jeśli Twój kod musi przejść typ parametru szablonu będzie się śmieszniejsze:
template <typename T>
T g() {
return T();
}
template <>
int g() {
return 0;
}
int g() {
return 1;
}
int main()
{
g<double>(); // return 0.0
g<int>(); // return 0
g(); // return 1 -- non-templated functions take precedence over templated ones
}
Wierzę, że "szablon <> void operator() (dane int) {" w sekcji kodu najwyższego powinien być "szablon <> void operator() (dane int) {", a w sekcji dolnej, "int g() {"powinno być" int () {"na dole (przepraszam, nie wiem jak stylizować sekcje kodu w komentarzach) –
Miałem wątpliwości, ale zarówno kompilatory GCC, jak i Comeau'a przyjmują kod jako ważny. Nie mogę przetestować MSVS teraz, jeśli możesz spróbować, byłbym wdzięczny :) –
nadal zajrzyj do odpowiedzi tutaj http://stackoverflow.com/questions/937744/function-template-specialization-format – stefanB