gpt4 book ai didi

c++ - 为什么默认参数不能依赖于非默认参数?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:12:38 25 4
gpt4 key购买 nike

考虑以下构造函数:

class MyClass {
MyClass(unsigned int dimension, std::vector vector=unitaryVector(dimension));
};

其中 unitaryVector(d) 是一个返回 d 维随机 std::vector 的函数。

这会产生以下编译器错误:

error: default argument references parameter 'dimension'
MyClass(unsigned int dimension, std::vector vector=unitaryVector(dimension));

为什么这个习语在 C++11 中无效?这似乎很明显:如果提供了 vector 参数,则将 vector 初始化为参数的拷贝,否则,调用函数并将其初始化为返回值的拷贝值(value)。为什么编译器不能理解这一点?

最佳答案

C++ 标准禁止这样做。

dcl.fct.default

9 default argument is evaluated each time the function is called with no argument for the corresponding parameter. A parameter shall not appear as a potentially-evaluated expression in a default argument. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names.

[ Example:

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)); // OK, unevaluated operand

— end example ]

请注意,如果未提供默认参数,则在调用站点替换

Intro.execution (强调我的)

11: [ Note: The evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default arguments ([dcl.fct.default]) are considered to be created in the expression that calls the function, not the expression that defines the default argument. — end note ]


您可以简单地重载构造函数并委托(delegate)它:

class MyClass {
explicit MyClass(unsigned int dimension)
: MyClass(dimension, unitaryVector(dimension)) //delegation
{ }
MyClass(unsigned int dimension, std::vector vector);
};

脚注:使单参数构造函数显式是一件好事

关于c++ - 为什么默认参数不能依赖于非默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37919291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com