为什么默认参数不能依赖非默认参数? [英] why can't default argument depend on non-default argument?

查看:63
本文介绍了为什么默认参数不能依赖非默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下构造函数:

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

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

where unitaryVector(d) is a function that returns a random std::vector in d dimensions.

这会导致以下编译器错误:

This gives the following compiler error:

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

为什么这个成语在C ++ 11中无效?这似乎很明显:如果提供了 vector 参数,则将 vector 用作参数的副本,否则,调用该函数并将其作为return的副本进行初始化价值.为什么编译器不能理解这一点?

Why isn't this idiom valid in C++11? It seems to be pretty obvious: if vector argument is provided, init vector as a copy of the argument, otherwise, call the function and init it as a copy of the return value. Why can't a compiler understand this?

推荐答案

C ++标准禁止使用它.

The C++ standard forbids it.

dcl.fct.default

9 默认参数每次调用该函数时都会被评估没有相应参数的参数.参数不得在默认参数中显示为可能评估的表达式.在默认参数之前声明的函数的参数位于范围,并且可以隐藏名称空间和类成员名称.

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.

[示例:

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

—结束示例]

请注意,如果未提供默认参数,则会在呼叫站点上替换

Note that default arguments are replaced at the call site if not provided

简介执行 (强调我的意思)

11: [注意: 完整表达式 的评估可以包括对以下子表达式的评估:在词汇上不是的一部分完整表达.例如,涉及评估的子表达式默认参数([dcl.fct.default])被认为是创建的在调用函数的表达式中,而不是定义默认参数. —尾注]

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 ]


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


You can simply overload the constructor and delegate it:

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

脚注:使单参数构造函数 explicit

这篇关于为什么默认参数不能依赖非默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆