Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function with a non-const pointer reolves to a template function over a function taking a pointer to const

Tags:

c++

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?

like image 375
Roland Avatar asked Jun 23 '11 23:06

Roland


1 Answers

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.

like image 50
Matteo Italia Avatar answered Sep 23 '22 21:09

Matteo Italia