The following code was compiled on g++ 4.1.2 and g++ 4.4.4. Both give the results noted in the comments.
int f(const int * a)
{
return 0;
}
template<typename A>
int f(A a)
{
return 1;
}
int main()
{
int x;
// return f(&x); // returns 1
return f((const int *)&x); // returns 0
}
It appears to boil down to a call of f(int *)
resolves to f<int *>(int *)
instead of the expected f(const int *)
. I found this shocking and completely unintuitive.
Is this a bug in g++, a dark corner of C++, or obvious for some reason I am missing? If it's not a bug, what's the theory or logic behind it? Are there any safe practices regarding this issue?
For the instantiated template f<int *>
no conversion (int *
->const int *
) is needed, so it's a better match - actually, it's an exact match, that would lose only against a non-templated exact match, which is what happens for the second call.
The full explanation of the "better match" rules is available at §13.3.3 of the C++ standard.
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