
▲ 1 r/cpp_questions
How do I Implement an interface with a lambda?
Consider the usual visitor pattern:
class FooA;
class FooB;
class FooVisitor {
public:
virtual auto accept(FooA&) -> void = 0;
virtual auto accept(FooB&) -> void = 0;
// etc.
virtual ~FooVisitor() = default;
};
class Foo {
public:
virtual auto visit(FooVisitor&) -> void = 0;
};
class FooA : public Foo {
auto visit(FooVisitor & visitor) -> void override { visitor.accept(*this); }
};
//etc.
Is there a way to pass a lambda (with captures) to the visit method? Something like this:
auto my_function() {
Foo& my_foo = get_foo();
int my_data[10] = {};
my_foo.visit([&](FooA& foo_a){ do_work(foo_a, my_data); });
}
I did some googling and found this video from jason turner which basically says it cant be done. Is there really no easy way to implement an interface with a lambda? The other option would be to define a local struct that implements `FooVisitor`, but having to capture things manually is a PITA.
Is there a better solution (which allows for runtime polymorphism) with C++20's concepts ?
u/FullaccessInReddit — 6 days ago