Search code examples
c++overloadingimplicit-conversionambiguity

Approaches on fixing the Ambiguity


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 ?


Solution

  • 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