Lambdas are delivering good and quick and simple C++. But , contrary to Functional Programming aficionados, you still need good old structs or classes. Here is the simple solution, with which you can achieve:
- mixing lambdas into structure at run-time
- polymorphic behavior without inheritance.
This solution is simple because it is not pathologically generic. For different struct you will need to code different mixer. If you expect hundreds of mixers this is not for you. Which, I very much doubt.
DBJ lambda mixer in action is here. (Wandbox). The code is also here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
// (c) 2020 by dbj@dbj.org // Licence CC BY SA 4.0 namespace dbj { // use-case: facade that can be painted and isolated // using different ways to do the job // here are the activities one does on a facade // in C++ parlance: stand alone functions // or lambdas or functors // for this poc we define activity as a lambda that // has no arguments and returns const char * inline auto acrilyc_painting = [] ( ) constexpr { return " Acrylic painted"; } ; inline auto dry_painting = [] ( ) constexpr { return " Dry painted"; } ; inline auto stirofoam_isolating = [] ( ) constexpr { return " Stirofoam isolated" ; } ; inline auto stone_wool_isolating = [] ( ) constexpr { return " Stone wool isolated" ; } ; // users use this lambda as the factory method // this is also a mixin pattern at work // delivering the facade required auto mixer = [ ] ( auto addr, auto painter, auto isolator ) { static auto enclosed_painter{painter} ; static auto enclosed_isolator{isolator} ; static auto address_{ addr } ; // local struct struct facade final { // error: local class shall not have static data member // error: non-static data member declared with placeholder 'auto' // error: use of parameter from containing function // ditto ... no can do // decltype(painter) enclosed_painter{painter} ; // decltype(isolator) enclosed_isolator{isolator} ; // decltype(addr) address_{ addr } ; constexpr auto address () const { return address_; } constexpr auto isolate ( ) { return enclosed_isolator(); } constexpr auto paint ( ) { return enclosed_painter(); } }; return facade{}; }; } // dbj |
Enjoy. As ever, comments bellow please.