我想用 boost::optional 重载,但由于重载歧义而不能,我正在寻找解决方法。
例如,下面的代码会因为歧义而无法通过编译:
void foo() { ... }
void foo(const Class& A) { ... }
// \deprecated
void foo(boost::optional<const Class&> A) { A ? foo(A) : foo() }
我想做这件奇怪的事情的原因是,由于 boost::optional 的右值/左值问题引起的错误,我正在用函数重载替换 boost::optional 实例。问题是发生了一些 API 损坏,所以我需要保留旧的函数定义。
API 损坏的一个例子是其他默认参数,
void foo(int a=0, boost::optional<Bar> A=boost::none, float b=0.0) { ... }
要求我切换参数的顺序:
void foo(int a=0, float b=0.0) { ... }
void foo(Bar A, int a=0, float b=0.0) { ... }
但现在打破的情况是
foo(1, boost::none, 3.14);
所以我想为这种类型的函数调用保留一个弃用的函数定义。有优雅的解决方法吗?
我想一个(丑陋的)可能性是
// \deprecated
void foo(int a, boost::optional<DummyClass> A, float b=0.0) { ... }
但这并不能激发喜悦。有什么想法吗?
最佳答案
正如评论中所述,您的常规案例有错字,会进行递归调用。固定版本:
void foo() { /*...*/ }
void foo(const Class& A) { /*...*/ }
[[deprecated]] void foo(boost::optional<const Class&> A) { A ? foo(*A) : foo(); }
I am replacing
boost::optional
instances with function overloads instead.
所以你可以替换:
void foo(int a=0, boost::optional<Bar> A=boost::none, float b=0.0) { /*...*/ }
通过
void foo(int a = 0) {/*..*/}
void foo(int a, Bar, float b = 0.0f) { /*..*/ }
void foo(int a, boost::none_t, float b = 0.0f) { /*..*/ }
[[deprecated]] void foo(int a, boost::optional<Bar>, float b = 0.0f);
关于c++ - 使用 boost::optional 重载歧义,解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596225/