Return type std::optional<std::variant<...>>

Viewed 3881

I have a situation where a function must return a value taken from a table. A cell in this table (let's assume the table just works...) may contain a value, or it might not. This value can also be one of several types: int, double, string, date (but no other type).

What would such a function return? Is it a good idea to return std::optional<std::variant<std::string, int, double, std::chrono::time_point>>?

Would that be a good use of optional and variant?

2 Answers

Just want to add that before C++17 and the standardization of variant and monostate, there is already boost::blank to solve the exact same issue for boost::variant.

By convention, if boost::blank is used, it should always be the first template argument, so that a default-constructed variant is empty and checking for emptyness is done with .which() == 0.

Related