4
#include <variant>


struct A
{
    void foo(){}
};


struct B
{
    void foo(){}
};

int main()
{
    std::variant< A, B > v{ A{} };
    v.foo();  // doesn't work
}

How do I use the std::variant value not knowing it's type but knowing it's properties? I believe this is called Generic Polymorphism equivalent to Duck Typing.

Vorac
  • 8,726
  • 11
  • 58
  • 101

1 Answers1

6

Totally valid use case. I imagine there's many ways to do it, but here's one:

std::visit([](auto&& val) { val.foo(); }, v);

Demo

The reason your initial code doesn't work is because A::foo is unrelated to B::foo, so to use them interchangeably you need a context where the type "containing" a foo member is deduced. In the visit example, we create such a context by making the callable a generic lambda.

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153