Inspired by the current top answer to this popular question concerning getting the larger of two values in C#.
Consider a function that accepts two integer pointers, and returns a pointer. Both pointers might be nullptr
.
const int* max(const int* a, const int* b);
If a or b is a nullptr
return the non-null pointer. If both are nullptr
, return nullptr
.
If both are valid pointers return max(*a, *b);
.
The currently most upvoted answer for the C# question is
int? c = a > b ? a ?? b : b ?? a;
int? represents a nullable value, not unlike a pointer.
How can this be expressed in an elegant and idiomatic fashion in c++?
My immediate attempt was along the lines of
const int* maxp(const int* a, const int* b){
if (!a) return b;
if (!b) return a;
return &std::max(*a, *b);
}