@std::optional can be used, but you'd have to set the default value in the function body which isn't where default values should be located in my opinion.
If there is a better way I'd love to know it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <optional> #include <string> void printWaldo(std::optional<std::string> optShirtColor, double dbX, double dbY) { std::string strShirtColor{ optShirtColor.value_or("red") }; std::cout << "Waldo is wearing a " << strShirtColor << " shirt and is located at " << dbX << ", " << dbY << std::endl; } int main(void) { printWaldo(std::nullopt, 12.3, 45.6); printWaldo("blue", 78.9, 1.2); return 0; } |
Output
Waldo is wearing a red shirt and is located at 12.3, 45.6
Waldo is wearing a blue shirt and is located at 78.9, 1.2