使用 nullptr 调用重载方法是不明确的

Call of overloaded method with nullptr is ambiguous

本文关键字:不明确 方法 重载 nullptr 调用 使用      更新时间:2023-10-16

我有一些覆盖的方法,它们采用一些不同的指针类型。
现在我想调用一个以nullptr作为参数的特定方法。

我知道我可以将nullptr转换为特定类型的指针,即我希望它调用 takes 的方法。
但我不想/不能投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;
}

如果我只是用nullptr调用它,我会
error: call of overloaded 'myMethod(std::nullptr_t)' is ambiguous
,因为编译器不知道它应该调用哪个方法。

有没有办法做我想做的事?
喜欢类似于模板专业化的东西?

您可以创建一个以std::nullptr_t作为参数的重载,然后在其中调用所需的确切函数(通过强制转换(:

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

您可以创建 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;
}

一些程序员有一个很好的建议,但如果你愿意在不传递nullptr的情况下调用它,你也可以为其中一个方法添加一个默认参数,如下所示:

void myMethod (Foo* = nullptr) {}
void myMethod (Bar*) {}
int main () {
myMethod();
}
喜欢类似于

模板专业化的东西?

如果这意味着您希望根据具体情况指定目标类,则可以将程序员 dude 的答案中的重载转换为模板@Some。

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

现在,您可以使用简单的模板名称来调用所需的重载

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.