I have the following program similar with my problem. I need to get the specific class from a method like getClass
and after that pass the object and call similar defined method. I can't use polymorphism.
#include <variant>
#include <optional>
#include <iostream>
using namespace std;
class A{
public:
void foo() const {
std::cout << "A";
}
};
class B{
public:
void foo() const {
std::cout << "B";
}
};
class C {
public:
void foo() const {
std::cout << "C";
}
};
using Object = std::variant<A,B,C>;
std::optional<Object> getClass(int nr)
{
if (nr == 0)
return A{};
else if (nr == 1)
return B{};
else if(nr == 2)
return C{};
return std::nullopt;
}
void f(const Object& ob)
{
//how to call foo function ???
}
int main()
{
const auto& obj = getClass(2);
if (obj.has_value())
f(obj.value());
}
CodePudding user response:
You can use std::visit
void f(const Object& ob)
{
std::visit([](const auto& o){ o.foo();},ob);
}