【问题标题】:In C++, does it make sense to use a function with std::optional<T> parameter, to denote optional parameters?在 C++ 中,使用带有 std::optional<T> 参数的函数来表示可选参数是否有意义?
【发布时间】:2020-07-03 21:03:01
【问题描述】:

我知道可以实现带有可选参数的函数,如下所示:

int someFunction(int A, int B = -1) {
   if (B != -1) {
       ... // If B given then do something
   } else { 
       ... // If B not given then do something else
   }
}

但是,我愿意按照同事的建议利用 std::optional 。这是我正在尝试做的,但我遇到了错误:

int some Function(int A, std::optional<int> B) {
    if (B.has_value()) {
        ... // If B given then do something
    } else { 
        ... // If B not given then do something else
    }
}

问题在于,在第一种方法中,我可以像 someFunction(5) 这样调用函数,C++ 会意识到我选择不使用可选参数。但是在第二种方法中,以同样的方式调用someFunction(5) 会产生错误too few arguments to function call

我希望能够在不包含可选参数的情况下使用第二种方法调用函数,这可能/推荐吗?

【问题讨论】:

  • 一个可选项通常表示值的存在/不存在(尤其是作为返回值),而 默认参数 是您在第一种情况下使用的。在这方面,它们是完全不同的概念

标签: c++ optional


【解决方案1】:

要以您在这里想要的方式使用它,我相信您需要指定默认值std::nullopt

int some Function(int A, std::optional<int> B = std::nullopt) {
    if (B.has_value()) {
        ... // If B given then do something
    } else { 
        ... // If B not given then do something else
    }
}

【讨论】:

    【解决方案2】:

    这真的没有意义;正常的解决方案是额外的重载int some Function(int A)

    【讨论】:

    • 你能解释一下为什么它没有意义吗?在我看来,使用 std::optional&lt;int&gt; B = std::nullopt 比使用 int B = -1 更“干净”,因为仍然可以使用 -1 调用该函数,并且该函数将像未使用可选参数一样执行。
    • @Minyc510 — 答案是建议两个重载:int someFunction(int a)int someFunction(int a, int b)
    • @Minyc510:你没有B 的默认值了。如果使用一个参数调用 Function,则会选择另一个重载,并且它甚至没有 B 参数。
    • 我明白了。在我的特殊情况下,这需要一些代码重复,所以我选择了接受的答案,这会导致代码更清晰。同样,至少对我而言。
    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多