c++ - 默认参数必须在编译时绑定(bind) - 为什么?

标签 c++ compilation default-value

<分区>

为什么 C++ 是这样设计的?...

(这个问题不同,但与

Not possible: this pointer as a default argument. Why? )

最佳答案

实际上,这并不完全准确。限制是:

8.3.6 默认参数 [dcl.fct.default]

7) Local variables shall not be used in a default argument. [ Example:

void f() {
int i;
extern void g(int x = i); //error
// ...
}

—end example ]

8) The keyword this shall not be used in a default argument of a member function. [ Example:

class A {
void f(A* p = this) { } // error
};

因此,this 和局部变量不能用作默认值。

例如,以下是有效的:

int a = 1;
int f(int);
int g(int x = f(a)); // default argument: f(::a)
void h() {
  a = 2;
  {
    int a = 3;
    g(); // g(f(::a))
  }
}

g 将使用值 f(2) 调用,这不是编译时常量。这是直接来自标准的示例。

出现这种情况的原因很常见:要么没有提案,要么被拒绝,认为没有必要或实现起来太困难。

关于c++ - 默认参数必须在编译时绑定(bind) - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903724/

相关文章:

c++ - 使用 weak_ptr 实现观察者模式

sql - 将可空列更改为具有默认值的 NOT NULL

c# - 具有 DefaultValueHandling 的 Newtonsoft json DeserializeObject 不适用于运行时对象

c++ - 在 TensorFlow 存储库之外构建 TensorFlow C++ 项目?

java - 无法找到 tools.jar

C++ 默认枚举值用法

c++ - Qt/C++ 将指针指向另一个构造函数

c++ - 在设备上的线性内存中循环二维数组时将 float* 转换为 char*

c++ - enable_shared_from_this 需要什么?

perl - 如果运行时与编译时相比相形见绌怎么办?