fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. struct interface {
  5. virtual int hello() = 0;
  6. };
  7.  
  8. struct implementation : public interface {
  9. virtual int hello() {
  10. std::cout << "hello()\n";
  11. return 42;
  12. }
  13. ~implementation() {
  14. std::cout << "~implementation()\n";
  15. }
  16. };
  17.  
  18. struct adapter {
  19. interface* obj;
  20.  
  21. adapter(std::function<int()>&& func) {
  22. struct lambda : public interface {
  23. std::function<int()> func;
  24. lambda(std::function<int()> func_): func(func_) { }
  25. virtual int hello() {
  26. return this->func();
  27. }
  28. };
  29. this->obj = new lambda{func};
  30. }
  31.  
  32. adapter(interface&& impl) {
  33. this->obj = &impl;
  34. }
  35. };
  36.  
  37. int main() {
  38. adapter a([]() { std::cout << "hello from lambda\n"; return 99; });
  39. a.obj->hello();
  40.  
  41. adapter b{implementation()};
  42. b.obj->hello();
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
hello from lambda
~implementation()
hello()