Mel*_* S. 4 c++ overloading nullptr
我有一些overloaed方法,它们采用了一些不同的指针类型.
现在我想将一个特定方法nullptr作为参数调用.
我知道我可以将其nullptr转换为特定类型的指针,我想要它调用的方法.
但我不想/不能投nullptr.
这个例子应该解释我想要做的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)
如果我只是用nullptr我得到它来调用它,
error: call of overloaded 'myMethod(std::nullptr_t)' is ambiguous
因为编译器不知道它应该调用哪个方法.
有办法做我想要的吗?
喜欢类似于模板专业化的东西?
你可以创建一个带std::nullptr_t参数的重载,然后在其中调用想要的精确函数(通过强制转换):
void myMethod(std::nullptr_t)
{
myMethod(static_cast<Foo*>(nullptr));
}
Run Code Online (Sandbox Code Playgroud)
您可以创建 Foo 和 Bar 的指针,并让它们都指向 nullptr。现在您可以通过传递指针变量作为参数来调用重载函数。
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
487 次 |
| 最近记录: |