模板实参推导失败,尝试使用std::variant



我有以下程序类似于我的问题。我需要从像getClass这样的方法中获得特定的类,然后传递对象并调用类似的定义方法。我不能使用多态性。

#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());
}

您可以使用std::visit

void f(const Object& ob)
{
std::visit([](const auto& o){ o.foo();},ob);
}