I created 4 classes:
class C1 {};
class C2 {};
class C3 {};
class C4 {};
And template functions based on these classes:
template<class T1, class T2>
T2 F() {
std::cout << "F<T1, T2>" << std::endl;
return T2();
}
template<class T>
T F();
template<>
C1 F<C1>() {
std::cout << "F<C1>" << std::endl;
return F<C3, C1>();
}
template<>
C2 F<C2>() {
std::cout << "F<C2>" << std::endl;
return F<C4, C2>();
}
This gives me compile error:
explicit specialization 'C1 F<C1>(void)' is not a specialization of a function template
explicit specialization 'C2 F<C2>(void)' is not a specialization of a function template
However, if I change the name of the 1st function F
to a different name F1
:
template<class T1, class T2>
T2 F1() {
std::cout << "F<T1, T2>" << std::endl;
return T2();
}
template<class T>
T F();
template<>
C1 F<C1>() {
std::cout << "F<C1>" << std::endl;
return F1<C3, C1>();
}
template<>
C2 F<C2>() {
std::cout << "F<C2>" << std::endl;
return F1<C4, C2>();
}
or change the return type of these functions to be the same (like int
):
template<class T1, class T2>
int F() {
std::cout << "F<T1, T2>" << std::endl;
return 5;
}
template<class T>
int F();
template<>
int F<C1>() {
std::cout << "F<C1>" << std::endl;
return F<C3, C1>();
}
template<>
int F<C2>() {
std::cout << "F<C2>" << std::endl;
return F<C4, C2>();
}
Then the compile succeeds, and I can successfully call:
F<C1>();
F<C2>();
And get expected output:
F<C1>
F<T1, T2>
F<C2>
F<T1, T2>
The question is why the 1st code doesn't compile but the 2nd and the 3rd code compiles.
In https://en.cppreference.com/w/cpp/language/function_template I found:
Two function templates with the same return type and the same parameter list are distinct and can be distinguished with explicit template argument list.
I guess that's why the 3rd code compiles as the return types are the same. But it doesn't explain why the 1st code doesn't compile just because the return types are different.
And even though it's because the return types can't be different, it doesn't explain why the 2nd code compiles as F<C1>
and F<C2>
has different return types there.
"... is not a specialization of ..."
errors that you claim, but instead I get"undefined reference to ..."
errors on actual calls toF<C1>()
andF<C2>()
.