When I say target-typing I mean using the type of the receiver variable or parameter as information to infer parts of the code I'm assigning to it. Like for example, in C# you'd write something like this to pass a nullable value or a null (empty) if necessary:
void f(int? i) {}
void caller(bool b) =>
f(b ? 5 : null); // value is bound to an int? parameter so all information
// to build this object is already in code
The best I could come up with in C++ is something like this:
void f(const optional<int>& i) {}
void caller(bool b)
{
f(b ? make_optional(5) : optional<int>());
}
And it works, but it requires me to write optional twice and provide the optional type once, even though all the information should already be in code. This is, in my humble opinion, what type inference should do for you without having to repeat yourself multiple times per line. And because the following does work:
optional<int> i;
i = {}; // empty
i = {5}; // a value
I'd have thought that the next logical step would also work:
void f(const optional<int>& i) {}
void caller(bool b)
{
f(b ? {5} : {}); // doesn't compile
}
So overall from various experiments it seems target-typing works when directly assigning a value to a variable, but not as part of a ternary conditional expression bound to a parameter? Am I understanding this correctly? There is no limit on the C++ version, I've been writing this in MS C++20 for instance.
And a related question, though not the main focus of my question, is there a better way of writing an optional<> initialization that can either have a value or not based on a boolean?