I have some variant using V = std::variant<A, B, C>
and a function with the prototype V parse(const json&)
. The function should try to parse all the types (e.g. A
, B
, then C
) till the first success (and it should do it implicitly, for there will be many types in time).
How to implement something of this kind?
We may use std::variant_size
somehow.
Here is something close to what I need.
My solution is to list parsers of all the types explicitly.
V parse(const json& i_j)
{
using Parser = std::function<MaybeV(const json&)>;
static const auto ps = std::vector<Parser>{
[](const auto& j)->MaybeV{return j.get<std::optional<A>>;},
[](const auto& j)->MaybeV{return j.get<std::optional<B>>;},
[](const auto& j)->MaybeV{return j.get<std::optional<C>>;}
};
for (const auto& p : ps)
if (auto opt_result = p(i_j))
return std::move(*opt_result);
throw ParseError("Can't parse");
}
Yet it may definitely be simplified, for the lambdas different only in type and what I actually need is to iterate over the types of std::variant
.