我有一堂简单的课:
class A {
public:
bool f(int* status = nullptr) noexcept {
if (status) *status = 1;
return true;
}
void f() {
throw std::make_pair<int, bool>(1, true);
}
};
int main() {
A a;
a.f(); // <- Ambiguity is here! I want to call 'void f()'
}
我想通过任何方式解决方法调用的歧义,以支持抛出异常的方法。
此类接口的基本原理:
noexcept(true)
and noexcept(false)
接口,noexcept(false)
变体中的指针有选择地获取额外的信息-而noexcept(true)
变体将始终将此信息打包在异常内。有可能吗?也欢迎提供更好的界面的建议。
如您所知,具有带有此类签名的功能显然是一个糟糕的设计。真正的解决方案是为其使用不同的名称,或者丢失默认参数,并已在其他答案中提出。
但是,如果您被接口所困,则不能更改,或者仅出于乐趣,这里可以显式调用void f()
:
技巧是使用函数指针强制转换来解决歧义:
a.f(); // <- ambiguity is here! I want to call 'void f()'
(a.*(static_cast<void (A::*)()>(&A::f)))(); // yep... that's the syntax... yeah...
好的,它可以工作,但是永远不要这样写代码!
有一些方法可以使其更具可读性。
// create a method pointer:
auto f_void = static_cast<void (A::*)()>(&A::f);
// the call is much much better, but still not as simple as `a.f()`
(a.*f_void)();
auto f_void = [] (A& a)
{
auto f_void = static_cast<void (A::*)()>(&A::f);
(a.*f_void)();
};
// or
void f_void(A& a)
{
auto f_void = static_cast<void (A::*)()>(&A::f);
(a.*f_void)();
};
f_void(a);
我不知道这是否更好。调用语法肯定更简单,但是当我们从方法调用语法切换为自由函数调用语法时,它可能会造成混淆。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句