In Python I can do something like:
def add_postfix(name: str, postfix: str = None):
if base is None:
postfix = some_computation_based_on_name(name)
return name + postfix
So I have an optional parameter which, if not provided, gets assigned a value. Notice that I don't have a constant default for postfix
. It needs to be calculated. (which is why I can't just have a default value).
In C++ I reached for std::optional and tried:
std::string add_postfix(const std::string& name, std::optional<const std::string&> postfix) {
if (!postfix.has_value()) { postfix.emplace("2") };
return name + postfix;
}
I'm now aware that this won't work because std::optional<T&>
is not a thing in C++. I'm fine with that.
But now what mechanism should I use to achieve the following:
- Maintain the benefits of const T&: no copy and don't modify the original.
- Don't have to make some other
postfix_
so that I have the optional one and the final one. - Don't have to overload.
- Have multiple of these optional parameters in one function signature.