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 geterror: 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?
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;
}
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