在 C++ 中,使用带有 std::optional<T> 参数的函数来表示可选参数是否有意义?

In C++, does it make sense to use a function with std::optional<T> parameter, to denote optional parameters?

我知道可以像这样实现带有可选参数的函数:

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.

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

要按照您想要的方式使用它,我相信您需要指定默认值 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
    }
}

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