0

I have been asked the following example to fix without modifying both function declaration and call.

void Display(int *nData)
{
}

void Display(float *fData)
{
}

int main()
{
    int a = 5;
    float b = 4.0f;

    Display(&a);
    Display(&b);
    Display(nullptr or NULL); // Ambiguity here, as nullptr or NULL (0) can be converted implicitly by compiler to both int and float

    return 0;
}

Any ideas ? Thanks

EDIT: Thanks for answers to fix this using std::nullptr_t with an overload, but what if the argument is "NULL" instead of nullptr ? How to fix that ?

Dinesh G
  • 129
  • 7
  • Can you add an overload of the function ? – nefas Aug 09 '17 at 16:24
  • Why would passing in `nullptr` here have any meaning? Defining your functions as `float&` and `int&` could avoid this, but if that's off the table that's harsh. You could call this failure a feature and be done with it. – tadman Aug 09 '17 at 16:24
  • @tadman I know we can fix that using reference, but I was asked by some one whether it is possible or not. – Dinesh G Aug 11 '17 at 03:28
  • @nefas Yes, we can add overload. – Dinesh G Aug 11 '17 at 03:31

2 Answers2

4

This can be fixed by adding a "dummy" overload taking a std::nullptr_t argument:

void Display(std::nullptr_t)
{
}

This will then be called when passing nullptr.


The macro NULL and the previous recommended null-pointer 0 are problematic though, as they will again introduce ambiguity.

Solving for 0 is easy, just add another overload taking a simple int (not a pointer) as argument. This might also solve the ambiguity with NULL but also might not.

The problem with the NULL macro is that it's implementation defined. It might be expanded as nullptr. It might be expanded as 0. Or it might be expanded to some other integer literal which evaluates as zero, but of an unknown type.

For example on my current system NULL is defined as 0LL, that is a long long int.

To handle all currently possible null pointers you need the following overloads:

void Display(std::nullptr_t);  // For nullptr
void Display(int);             // For 0 and some implementations of NULL
void Display(long);            // For some implementations of NULL
void Display(long long);       // For some implementations of NULL
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You could use nullptr_t with another overload:

void Display(std::nullptr_t nullData)
{
    // Handle special case of nullptr
}
user0042
  • 7,917
  • 3
  • 24
  • 39