Call of overloaded method with nullptr is ambiguous

Viewed 1938

I have some overloaed methods which take some different pointer types.
Now I want to call one specific method with nullptr as a parameter.

I know that I could cast the nullptr to the specific type of pointer, the method I want it to call takes.
But I don't want to/can't cast the nullptr.

This example shoud explain what I am trying to do:

class Foo {
    //some attributes
};
class Bar {
    //some attributes
};

void myMethod (Foo*) {
    //I want this method to be called
}
void myMethod (Bar*) {
    //Not this one
}

int main () {
    myMethod(nullptr);              //Something like this
//  myMethod(static_cast<nullptr>); //I don't want to write this.

    return 0;
}

If I just call it with the nullptr I get
error: call of overloaded 'myMethod(std::nullptr_t)' is ambiguous
because the compiler doesn't know which of the methods it should call.

Is there a way to do what I want?
Like something similar to the template specialization?

4 Answers

You can create an overload which take std::nullptr_t as argument, and then in it call the exact function wanted (through casting):

void myMethod(std::nullptr_t)
{
    myMethod(static_cast<Foo*>(nullptr));
}

You can create pointer of Foo and Bar and let both point to nullptr. Now you can call a overloaded function by passing pointer variable as argument.

class Foo {
    //some attributes
};
class Bar {
    //some attributes
};

void myMethod (Foo*) {
    //I want this method to be called
}
void myMethod (Bar*) {
    //Not this one
}

int main () {
    Foo* foo=nullptr;
    Bar* bar=nullptr;
    myMethod(foo);              //This will call myMethod(Foo*)

    return 0;
}

Some programmer dude has a good suggestion, but you could also add a default parameter to one of your methods if you were happy to call it without passing nullptr, like so:

void myMethod (Foo* = nullptr) {}
void myMethod (Bar*) {}

int main () {
    myMethod();
}

Like something similar to the template specialization?

If that means that you wish to specify the target class on a case by case basis, you can turn the overload in @Some programmer dude's answer into a template.

template<class C>
void myMethod(std::nullptr_t) {
    myMethod(static_cast<C*>(nullptr));
}

Now you can use a simple template name to call the overload you want

myMethod<Foo>(nullptr); // What you want now.
myMethod<Bar>(nullptr); // What you may want at another point.
myMethod<Baz>(nullptr); // What you may want sometime in the future,
                        // after adding another overload.
Related