I am trying to understand what the currenct C++14 standard says about resolving an ambiguous function call, mostly because I am seeing a difference between GCC 4.9.1, and Visual Studio 2013 update 3
Here's the code (exactly the same for both MS and GCC):
#include <iostream>
using namespace std;
void f(char *str, int chars) { cout << "f(char*, int)"; }
void f(char *first, char *second) { cout << "f(char*, char*)"; }
int main()
{
char *hello = "Hello, World";
f(hello, NULL); //which f gets called?
char c; cin.get(c);
return 0;
}
Visual Studio calls f(char*, int)
using default vs flags
GCC gives me a compiler error: call of overloaded 'f(char*&, NULL)' is ambiguous. gcc using only the -std=c++11
flag.
It depends on what NULL
is defined to be.
MSVC defines it as 0
, so the int
overload is an exact match and is preferred.
GCC defines it as the compiler internal __null
, causing an ambiguity on 64-bit because __null
's type there is long
. (It appears that __null
's type is int
on 32-bit, so it picks the int
overload when compiling for 32-bit.)
The standard permits NULL
to be defined as any C++ null pointer constant, including nullptr
, in which case it would unambigously pick the two pointer overload, or 0L
, which would be once again ambiguous (as going from a long
to both int
and char *
involves a conversion).
The moral: Don't use NULL
for a null pointer. Use nullptr
.
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