I'm stumped that after some code refactoring, the following piece of code does not work anymore as in it jumps to the auto, auto
case and ignores the Complex, Complex
one. I admittedly don't quite understand what the overload is exactly doing, but to me, the two codes look exactly the same, with the exception, that one gets its parameters directly whereas the other one has the parameters defined in the function body itself.
Math_Node Function_Manager::add(const Math_Node& arg){
Math_Object obj1 = arg.children_ptr()->at(0)->data();
Math_Object obj2 = arg.children_ptr()->at(1)->data();
if( std::holds_alternative<Complex>(obj1) ){
std::cerr << "obj1 is complex\n";
}
if( std::holds_alternative<Complex>(obj2) ){
std::cerr << "obj2 is complex\n";
}
return std::visit(overload{
[](const Complex& a, const Complex& b) -> Math_Object{
std::cerr << "COMPLEX ADD_\n";
return add_(a, b);
}
, [](const Matrix& a, const Matrix& b) -> Math_Object{
std::cerr << "MATRIX ADD_\n";
return add_(a, b);
}
, [&arg](auto& a, auto& b) -> Math_Node{
std::cerr << "NOT FOUND\n";
return arg;
}
}, obj1, obj2);
}
The code prints
obj1 is complex
obj2 is complex
NOT FOUND
This was the working code before refactoring:
Math_Object Function_Manager::add(const Math_Object& arg0, const Math_Object& arg1){
return
std::visit(
overload{
[](const Complex& a, const Complex& b) -> Math_Object{ return add_(a, b); }
, [](const Matrix& a, const Matrix& b) -> Math_Object{ return add_(a, b); }
, [](auto& a, auto& b) -> Math_Object{
throw std::runtime_error(
("Unsupported arguments for add: " + to_string(a) + to_string(b)).c_str());
}
}, arg0, arg1
);
}
The only thing I could come up with was that obj1
and obj2
are not really of the desired types, but the print to std::cerr
proves that they are. So why does std::visit not recognise it as such and how can I fix it?