我假设该函数已经有一个返回值,因此无法添加。
我想出的解决这个问题的方法是添加额外的指针参数,默认为 nullptr。
之前:
bool fun(double a, std::vector<std::randomexample> const & b)
之后:
bool fun(double a, std::vector<std::randomexample> const & b, int* extraoutput = nullptr)
然后像这样使用它
if(extraoutput)
*extraoutput = whatever;
但这正是我想出的。 我想知道是否有更好的方法来做到这一点。请注意,函数中已经包含“whatever”。
最佳答案
如果出于某种原因您需要二进制以及(主要)源兼容性[*]:
之前:
bool fun(double a, std::vector<std::randomexample> const & b) {
// do stuff
return true;
}
之后:
bool fun(double a, std::vector<std::randomexample> const & b, int* extraoutput) {
// do stuff
if(extraoutput)
*extraoutput = whatever;
return true;
}
bool fun(double a, std::vector<std::randomexample> const & b) {
return fun(a, b, nullptr);
}
如果您不想函数重载(例如,如果 fun
是 extern "C"
接口(interface)的一部分),那么您实际上不必调用新函数 fun
。它也可以是 fun2
。
[*] 正如 AndreyT 指出的那样,您的解决方案的源兼容性是有限的。对旧函数的调用将正常调用新函数,但您可能对旧函数执行的某些其他操作将无法正常工作(因为您已更改其类型)。
实际上我的代码中也存在源代码不兼容问题。 void(*foo)() = (void(*)()) fun;
在添加重载之前是允许的,但之后它就不明确了。如果您想支持这样做的代码,那么这是不希望函数重载的第二个原因。
关于c++ - 如何在不破坏现有代码的情况下向函数添加输出参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294477/