为什么现有的函数参数不能用于评估其他默认参数?

iam*_*ind 6 c++ compiler-errors function language-lawyer default-arguments

我在写一个函数foo()这需要2个const char*S作为参数,pBeginpEnd.foo()传递一个以null结尾的字符串.默认情况下,pEnd指向\0字符串的(最后一个字符).

void foo (const char *pBegin,
          const char *pEnd = strchr(pBegin, 0))  // <--- Error
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,我在上面的行中收到错误:

error: local variable ‘pBegin’ may not appear in this context
Run Code Online (Sandbox Code Playgroud)

为什么编译器不允许这样的操作?什么是潜在的问题?

In *_*ico 9

该标准不仅明确禁止在默认参数表达式中使用其他参数,还解释了原因并给出了一个示例:

ISO/IEC 14882:2003(E) - 8.3.6默认参数[dcl.fct.default]

9.每次调用函数时都会计算默认参数. 函数参数的评估顺序未指定.因此,函数的参数不应在默认参数表达式中使用,即使它们未被计算.在默认参数表达式之前声明的函数的参数在范围内,并且可以隐藏名称空间和类成员名称.[例:

    int a;
    int f(int a, int b = a);         // error: parameter a
                                     // used as default argument
    typedef int I;
    int g(float I, int b = I(2));    // error: parameter I found
    int h(int a, int b = sizeof(a)); // error, parameter a used
                                     // in default argument
Run Code Online (Sandbox Code Playgroud)

- 示例] ......


Bo *_*son 6

该语言仍然提供了一种方法来做你想要的 - 使用重载函数:

void foo (const char *pBegin, const char *pEnd)
{
   //...
}

void foo (const char *pBegin)
{ foo(pBegin, strchr(pBegin, 0)); }
Run Code Online (Sandbox Code Playgroud)