C++:在现实世界中添加和重新定义默认参数

C++: Adding and redefinition of default arguments in real world

可以在 C++ 中添加或重新定义函数的默认参数。我们来看例子:

void foo(int a, int b, int c = -1) {
    std::cout << "foo(" << a << ", " << b << ", " << c << ")\n";
}

int main() {
    foo(1, 2);   // output: foo(1, 2, -1)

    // void foo(int a, int b = 0, int c);
    // error: does not use default from surrounding scope

    void foo(int a, int b, int c = 30);
    foo(1, 2);   // output: foo(1, 2, 30) 

    // void foo(int a, int b, int c = 35);
    // error: we cannot redefine the argument in the same scope

    // has a default argument for c from a previous declaration
    void foo(int a, int b = 20, int c);
    foo(1);      // output: foo(1, 20, 30)

    void foo(int a = 10, int b, int c);
    foo();       // output: foo(10, 20, 30)

    {
        // in inner scopes we can completely redefine them
        void foo(int a, int b = 4, int c = 8);
        foo(2);  // output: foo(2, 4, 8)
    }

    return 0;
}

在线版本:http://ideone.com/vdfs3t

这些可能性由 8.3.6 中的标准规定。更具体的细节在8.3.6/4

For non-template functions, default arguments can be added in later declarations of a function in the same scope. Declarations in different scopes have completely distinct sets of default arguments. That is, declarations in inner scopes do not acquire default arguments from declarations in outer scopes, and vice versa. In a given function declaration, each parameter subsequent to a parameter with a default argument shall have a default argument supplied in this or a previous declaration or shall be a function parameter pack. A default argument shall not be redefined by a later declaration (not even to the same value) ...

说实话,我在用 C++ 编写代码时从未使用过此功能。我多次使用类似的代码片段让我的同事大吃一惊,但肯定不是在生产代码中。因此,问题是:您是否知道使用这些功能并带来好处的代码的真实示例?

如果您无法更改某些现有代码或库,并且您真的懒得输入正确的参数,那么更改某些范围的默认参数可能是一个解决方案。

这似乎是一种在处理由某些遗留工具生成的 C++ 代码时可能有用的技巧。例如,如果生成的代码总是使用默认参数对某些外部库进行数百次调用,但现在默认参数不再正确。