std::optional 是否更改函数的签名?

Does std::optional change signature of the function?

我需要在我的函数中创建一个带有默认值的可选参数。目前签名看起来像这样:

void func(int a, std::optional<int> b = 10)

函数的行为如下:

func(15, 5); // works
func(15);    // works 

问题是:如果我删除可选参数的显式初始化,如下所示:

void func(int a, std::optional<int> b)

然后函数的签名好像变了

func(15, 5); // works
func(15);    // fails 

这首先让我对 std::optional 的目的感到非常困惑。如果不是为了创建可选参数,它有什么用?

std::optional<int> 尽管是 "optional" 仍然是具体类型,因此,除非您在函数规范中有默认值,否则您需要提供一个。

似乎在此处混淆了可选的两个定义:

  • 允许您存储对象或缺少对象的具体类型;和
  • 函数参数的可选性(如果这是一个真实的词)。

它们不是一回事。

What is it good for if not for creating optional arguments?

std::optional is not supposed to be used for optional argument what you expect; which requires default argument 正如您的第一个代码示例所示,std::optional 不会更改语言语法。

The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.

你可以像这样使用它

void func(int a, std::optional<int> b = std::nullopt) {
    if (b) {
        // if b contains a value
        ...
    } else {
        ...
    }
}

然后

func(15, 5); // b will contain a value (i.e. `5`)
func(15);    // b doesn't contain a value

另一个用途:可选return值:

// throws if cannot parse
auto parse_int(const std::string& s) -> int;

// returns std::nullopt if it cannot parse
auto try_parse_int(const std::string& s) -> std::optional<int>