如何在不破坏现有代码的情况下向函数添加输出参数?

Sar*_*ien 5 c++ parameters function

我假设函数已经有一个返回值,因此无法添加.

我想出来解决这个问题的方法是添加额外的指针参数,默认为nullptr.

之前:

bool fun(double a, std::vector<std::randomexample> const & b)
Run Code Online (Sandbox Code Playgroud)

后:

bool fun(double a, std::vector<std::randomexample> const & b, int* extraoutput = nullptr)
Run Code Online (Sandbox Code Playgroud)

并像这样使用它

if(extraoutput)
  *extraoutput = whatever;
Run Code Online (Sandbox Code Playgroud)

但这正是我提出的.我想知道是否有更好的方法来做到这一点.请注意,函数中已经存在"无论什么".

Ste*_*sop 4

如果由于某种原因您需要二进制以及(主要)源兼容性[*]:

前:

bool fun(double a, std::vector<std::randomexample> const & b) {
    // do stuff
    return true;
}
Run Code Online (Sandbox Code Playgroud)

后:

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);
}
Run Code Online (Sandbox Code Playgroud)

如果您不希望函数重载(例如,如果fun是接口的一部分extern "C"),那么您实际上不必调用新函数fun。也可能是这样fun2

[*] 正如 AndreyT 指出的,您的解决方案的源兼容性是有限的。对旧函数的调用将很好地调用新函数,但是您可能对旧函数执行的其他一些操作将无法正常工作(因为您已经更改了其类型)。

我的代码中实际上也存在源不兼容问题。void(*foo)() = (void(*)()) fun;在添加重载之前是允许的,但之后它是不明确的。如果您想支持执行此操作的代码,那么这是不希望函数重载的第二个原因。