我有一些变体using V = std::variant<A, B, C>
和原型的功能V parse(const json&)
。该函数应该尝试解析所有类型(例如A
, B
, then C
)直到第一次成功(并且应该隐式地解析,因为及时会有很多类型)。
如何实现这种东西?
我们可能想办法使用std::variant_size
。
这是接近我需要的东西。
我的解决方案是明确列出所有类型的解析器。
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");
}
然而,它肯定会被简化,因为 lambdas 仅在类型上有所不同,而我真正需要的是迭代std::variant
.