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
>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.