返回类型std :: optional< std :: variant< ...> [英] Return type std::optional<std::variant<...>>
问题描述
我遇到一种情况,即函数必须返回从表中获取的值.该表中的一个单元格(假设该表可以正常工作...)可能包含一个值,也可能没有.此值也可以是以下几种类型之一:int, double, string, date
(但没有其他类型).
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).
这样的函数会返回什么?返回std::optional<std::variant<std::string, int, double, std::chrono::time_point>>
是个好主意吗?
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>>
?
optional
和variant
会很好用吗?
推荐答案
我认为这是std::monostate
的有用用法.具体来说,是variant<std::monostate, int, double, std::string, std::chrono::time_point>
. monostate
对于variant
可能不包含值的情况很有用.
I would consider this to be a useful use of std::monostate
. Specifically, variant<std::monostate, int, double, std::string, std::chrono::time_point>
. monostate
is useful for cases where a variant
may not contain a value.
关于使用实际类型而不是optional<variant>
的好处是,访问可以在其上正常进行.您可以编写一个可以使用monostate
参数的函子,从而甚至可以将visit
用于空"变体.
The nice thing about using an actual type rather than optional<variant>
is that visitation works normally on it. You can write a functor that can take a monostate
parameter, thus allowing you to use visit
for even "empty" variants.
这篇关于返回类型std :: optional< std :: variant< ...>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!