The pattern that a lot of people use with C++17 / boost variants looks very similar to switch statements. For example: (snippet from cppreference.com)
std::varia
You may add an extra layer to add those extra check, for example something like:
template struct IVisitorHelper;
template struct IVisitorHelper {};
template
struct IVisitorHelper
{
virtual ~IVisitorHelper() = default;
virtual Ret operator()(T) const = 0;
};
template
struct IVisitorHelper : IVisitorHelper
{
using IVisitorHelper::operator();
virtual Ret operator()(T) const = 0;
};
template struct IVarianVisitor;
template
struct IVarianVisitor> : IVisitorHelper
{
};
template
Ret my_visit(const IVarianVisitor>& v, V&& var)
{
return std::visit(v, var);
}
With usage:
struct Visitor : IVarianVisitor>
{
void operator() (double) const override { std::cout << "double\n"; }
void operator() (std::string) const override { std::cout << "string\n"; }
};
std::variant v = //...;
my_visit(Visitor{}, v);