← 模式
可选参数
1234567891011121314 | #include <optional> void foo(int i, std::optional<double> f, std::optional<bool> b) { } int main() { foo(5, 1.0, true); foo(5, std::nullopt, true); foo(5, 1.0, std::nullopt); foo(5, std::nullopt, std::nullopt); } |
此模式采用 CC0 公共领域贡献 许可。
需要 c++17 或更新版本。
意图
允许在调用函数时省略某些参数的值。
描述
在第 3-6 行的函数 foo
接受三个参数,其中两个的类型为 std::optional
。这使得这些参数的值可以被省略,如第 10-13 行所示,其中 std::nullopt
代表空值。
这种方法比使用指针和 nullptr
更具表现力。另一种相关技术是使用默认参数,它允许完全省略参数,但只能从参数列表的末尾开始省略。
如果你正在构造一个具有复杂可选参数组合的对象,请考虑使用建造者模式。