How to make a safer C++ variant visitor, similar to switch statements?

后端 未结 2 532
孤城傲影
孤城傲影 2021-02-02 08:41

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         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-02 09:00

    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);
    

提交回复
热议问题