Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct use of std::variant and std::visit when functor requires multiple arguments

I have been struggling a bit to get my code using std::variant in combination with std::visit to work. I have now reduced my code to a minimum of just using one type in my variant and still the compiler complains about no matching call to visit.

#include <iostream>
#include <variant>
#include <vector>
#include <array>
class SomeClass {
    
    public:
    
    std::vector<int> foo(const std::string& s, const std::array<float, 3>& d){
        return {};
    }
};

struct Visitor{
    public:
    
    std::vector<int> operator() (SomeClass& c1, const std::string& s, const std::array<float, 3>& a) {
        
        return c1.foo(s, a);        
        
    }
};

int main() {
    
    std::variant<SomeClass> variants;
    
    std::string s = "c++";
    std::array<float, 3> a {1, 0, 0};
    
    std::visit(Visitor{}, variants, s, a);

    return 0;
}

In am using gcc 11.3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

std::visit calls the visitor by always passing a single argument to the visitor: the object the visitor is visiting.

Additional parameters to std::visit are additional variants to visit.

std::visit(Visitor{}, variants, s, a);

This means: use the visitor{} to visit variants, then visit s, then finally a. All of these are expected to be, themselves, variants.

In other words: std::visit does not work the way you thought it worked. You’ll need to come up with some other, alternative, means to visit your variants.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading