I've been trying to understand template specializations. Why is this generating an error (specialization of 'T foo(T, T) [with T = int]' after instantiation
)
template <class T> T foo(T a, T b);
int main()
{
int x=34, y=54;
cout<<foo(x, y);
}
template <class T> T foo(T a, T b)
{
return a+b;
}
template <> int foo<int>(int a, int b)
{
cout<<"int specialization";
}
The standard demands that all template definitions must be known at the time of instantiation, and that every translation unit see the same definition. Otherwise your program is ill-formed (and in fact no diagnostic is required).
(So to solve this, just put all the template definitions at the top of the program.)
Remember that template functions aren't functions, just templates. Think of them as a code generation tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With