Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call of overloaded method with nullptr is ambiguous

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?

like image 844
Melvin S. Avatar asked Aug 28 '18 10:08

Melvin S.


2 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));
}
like image 112
Some programmer dude Avatar answered Sep 21 '22 17:09

Some programmer dude


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;
}
like image 39
rajenpandit Avatar answered Sep 24 '22 17:09

rajenpandit