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

我怕爱的太早我们不能终老 提交于 2019-12-05 05:36:24

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!