| [ Web Proxy ] |
| Viewing: https://cpppatterns.com/patterns/optional-arguments.html | [Back] [Original] |
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);
} |
This pattern is licensed under the CC0 Public Domain Dedication.
Allow argument values to be omitted when calling a function.
The function foo, on lines 36, takes three arguments, two of which
have type std::optional (from
the Library Fundamentals TS). This allows the value of those
arguments to be omitted, as shown on lines 1013, where
std::nullopt represents no value.
This approach is more expressive than using pointers and nullptr.
A related technique is the use of default arguments, which allow
arguments to be omitted entirely, but only from the end of the
argument list.
If you are constructing an object with a complex combinatorial set of optional arguments, consider using the builder pattern.
Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.
| Web Proxy Viewer | New URL | Original Page |