I have the following code:
class multitype {
public:
int get_number() const;
.....
private:
std::variant<int, std::string, ..... > field;
};
.....
struct zero_return {
template<typename X> int operator()(const X&) const { return 0; }
};
inline int multitype::get_number() const
{
struct visitor : public zero_return {
int operator()(int n) const { return n; }
};
return std::visit(visitor(), field);
}
While the actual code has many more types in the std::variant
and is much more complex, the above code fragment is sufficient to reproduce the issue by itself.
The idea behind the zero_return
struct in this example was supposed to provide a particular default return value for any type not specifically handled by a subclass functor.
However, the line with the call to std::visit fails with the following message:
error: no matching function for call to '__invoke(multitype::get_number() const::visitor, const std::__cxx11::basic_string<char>&)'
972 | return std::__invoke(std::forward<_Visitor>(__visitor),
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
973 | __element_by_index_or_cookie<__indices>(
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
974 | std::forward<_Variants>(__vars))...);
Can anyone please tell me what am I doing wrong?