I wrote a short example of the confusion that I'm having here:
#include <iostream>
template <typename T>
T Add (T t1, T t2)
{
std::cout << "<typename T>" << std::endl ;
return t1 + t2 ;
}
template <int>
int Add (int n1, int n2)
{
std::cout << "<int>" << std::endl ;
return n1 + n2 ;
}
template <>
int Add (int n1, int n2)
{
std::cout << "<>" << std::endl ;
return n1 + n2 ;
}
int main (void)
{
Add (5, 4) ;
Add <int> (5, 4) ;
Add <> (5, 4) ;
return 0 ;
}
The output of this is:
<>
<>
<>
So I'm thinking, okay, the most explicit specialization gets priority.
But then I remove:
template <>
int Add (int n1, int n2)
{
std::cout << "<>" << std::endl ;
return n1 + n2 ;
}
And the output is:
<typename T>
<typename T>
<typename T>
Why doesn't template <int>
version get called?
What would cause it to get called?
Why is the purpose of that syntax?
The second overload expects an integer, not a type. You'd call it with
Add< 42 >( 1, 2 );
Live example
To clarify: The second is an independent overloaded function called Add
, not a specialization. You were probably thinking of something like:
template <>
int Add<int>(int n1, int n2)
{
std::cout << "<T=int>" << std::endl ;
return n1 + n2 ;
}
which is exactly the same as the last specialization you wrote and which would thus conflict with it (redefining it). Live example
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