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

DAl*_*Ale 15 c++ language-features default-arguments

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

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

这些可能性受8.3.6中的标准规定.更具体的细节见8.3.6/4

对于非模板函数,可以在稍后的同一范围内的函数声明中添加默认参数.不同范围内的声明具有完全不同的默认参数集.也就是说,内部作用域中的声明不从外部作用域中的声明中获取默认参数,反之亦然.在给定的函数声明中,具有默认参数的参数之后的每个参数都应具有在此声明或先前声明中提供的默认参数,或者应为函数参数包.默认参数不应由后来的声明(甚至不是相同的值)重新定义......

说实话,我在c ++中编码时从不使用此功能.我多次使用类似的代码片段给同事们带来惊喜,但肯定不会出现在生产代码中.因此,问题是:您是否知道使用这些功能的代码的真实世界示例?

sno*_*ion 2

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

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