template<typename T>
void func(const T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func(const int &x) {
cout << "int specialization "<<x<<"\n";
}
template<>
void func(const double &x) {
cout << "double specialization "<<x<<"\n";
}
int main() {
int five = 5;
func(five); // prints int specialization 5
double d = 3.14;
func<int>(d); // prints int specialization 3
}
Now with const
removed
template<typename T>
void func( T &x) {
cout << "base template "<<x<<"\n";
}
template<>
void func( int &x) {
cout << "int specialization "<<x<<"\n";
}
template<>
void func( double &x) {
cout << "double specialization "<<x<<"\n";
}
int main() {
int five = 5;
func(five); // prints int specialization 5
double d = 3.14;
func<int>(d); // throws compile error
}
Why do I get a compilation error in func<int>(d)
where as in the const
version everything compiled fine ?
Error C2664 'void func(int &)': cannot convert argument 1 from 'double' to 'int &'
I came across this when I was trying out some examples on my own for template specialization.
I'm looking for reading links and posts that might be helpful.
const
allows to modifyx
, and this is a problem because thed
that you pass as an argument is not actually anint
(but adouble
). Usingconst
allows to bind to a temporary that is the result of converting youtdouble d
toint
.void func(int&)
and call it withfunc(d);
.template <typename T> struct temp { T var; temp(T value) : var{value} {} operator T&() { return var; } };
and then call the function byfunc<int>(temp<int>(d));
. Don't do this in real code; shown here for educational purposes.