Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual function implementation through lambda

Can I implement a pure virtual function using lambda, similar to Java interface implementations?

like image 607
Alexander Argyriou Avatar asked Jul 01 '20 12:07

Alexander Argyriou


1 Answers

Not directly. You can via some indirection though.

struct interface {
    virtual auto execute() -> int = 0;
};

template<typename T>
struct lambda_impl : interface, private T {
    lambda_impl(T l) noexcept : T{l} {}

    auto execute() -> int override {
        return T::operator()();
    }
};

You can now construct a lambda_impl like so:

auto instance = lambda_impl{
    []{ return 42; }
};

instance.execute();
like image 87
Guillaume Racicot Avatar answered Sep 29 '22 06:09

Guillaume Racicot