【发布时间】:2021-02-23 00:01:14
【问题描述】:
我想我明白为什么 C++ 不允许 local 变量作为默认函数参数:
int main () {
auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但即使该变量是 constexpr local 也是不允许的:
int main () {
constexpr auto local{1024};
auto lambda = [](auto arg1 = local){}; // "illegal use of local variable as default parameter"
}
但是,全局变量(即使是非constexpr)是允许的:
int global;
int main () {
auto lambda = [](int arg1 = global){}; // OK
}
有人可以解释在这种情况下不允许 constexpr 局部变量的理由吗?当默认值是固定的并且在编译时已知时,编译器似乎应该能够为函数构造适当的“默认参数”重载。
【问题讨论】:
-
你可以制作本地的
static,除了一些奇怪的递归情况外,这通常是个好主意。
标签: c++ constexpr default-arguments