Can I implement a pure virtual function using lambda, similar to Java interface implementations?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With