Using std::visit on a class inheriting from std::variant - libstdc++ vs libc++

前端 未结 3 452
忘了有多久
忘了有多久 2021-01-01 11:28

Consider the following code snippet:

struct v : std::variant> { };

int main()
{
    std::visit([](auto){ }, v{0});
}
         


        
3条回答
  •  长情又很酷
    2021-01-01 12:09

    I came across this issue as well recently. I kind of came up with a workaround which basically specialises variant_size and variant_alternative for the class that inherits from the variant..

    link on godbolt

    Its not pretty and it injects stuff into the std namespace. I'm not a metaprogramming expert (yet!) so its something I hacked together. Maybe someone else can improve on this?

    #include 
    #include 
    #include 
    #include 
    
    #include 
    #include 
    
    
    
    using var = std::variant;
    
    struct myvar : public var {
        using var::var;
        using var::operator=;
    
    };
    
    namespace std{
    
        template<>
        struct variant_size : variant_size {
        };
    
        template
        struct variant_alternative :  variant_alternative {
        };
    }
    
    int main(){
    
        constexpr int vs = std::variant_size::value;
    
        myvar s = std::string{"boo!"}; 
        std::visit([](auto&& e){std::cout << e << "\n";}, s);
        std::cout << vs;
    }
    
    

提交回复
热议问题