1 /* Copyright 2016-2017 Joaquin M Lopez Munoz. 2 * Distributed under the Boost Software License, Version 1.0. 3 * (See accompanying file LICENSE_1_0.txt or copy at 4 * http://www.boost.org/LICENSE_1_0.txt) 5 * 6 * See http://www.boost.org/libs/poly_collection for library home page. 7 */ 8 9 /* basic usage of boost::function_collection */ 10 11 #include <boost/poly_collection/function_collection.hpp> 12 #include <functional> 13 #include <memory> 14 #include <random> 15 #include <vector> 16 #include "rolegame.hpp" 17 main()18int main() 19 { 20 //[basic_function_1 21 std::vector<std::unique_ptr<sprite>> sprs; 22 std::vector<std::string> msgs; 23 std::vector<window> wnds; 24 //] 25 26 // populate sprs 27 std::mt19937 gen{92748}; // some arbitrary random seed 28 std::discrete_distribution<> rnd{{1,1,1}}; 29 for(int i=0;i<4;++i){ // assign each type with 1/3 probability 30 switch(rnd(gen)){ 31 case 0: sprs.push_back(std::make_unique<warrior>(i));;break; 32 case 1: sprs.push_back(std::make_unique<juggernaut>(i));break; 33 case 2: sprs.push_back(std::make_unique<goblin>(i));break; 34 } 35 } 36 37 // populate msgs 38 msgs.push_back("\"stamina: 10,000\""); 39 msgs.push_back("\"game over\""); 40 41 // populate wnds 42 wnds.emplace_back("pop-up 1"); 43 wnds.emplace_back("pop-up 2"); 44 45 //[basic_function_2 46 //= #include <boost/poly_collection/function_collection.hpp> 47 //= ... 48 //= 49 // function signature accepting std::ostream& and returning nothing 50 using render_callback=void(std::ostream&); 51 52 boost::function_collection<render_callback> c; 53 //] 54 55 //[basic_function_3 56 //<- 57 auto render_sprite=[](const sprite& s){ 58 //-> 59 //= auto render_sprite(const sprite& s){ 60 return [&](std::ostream& os){s.render(os);}; 61 }/*<-*/;/*->*/ 62 63 //<- 64 auto render_message=[](const std::string& m){ 65 //-> 66 //= auto render_message(const std::string& m){ 67 return [&](std::ostream& os){os<<m;}; 68 }/*<-*/;/*->*/ 69 70 //<- 71 auto render_window=[](const window& w){ 72 //-> 73 //= auto render_window(const window& w){ 74 return [&](std::ostream& os){w.display(os);}; 75 }/*<-*/;/*->*/ 76 //= ... 77 //= 78 for(const auto& ps:sprs)c.insert(render_sprite(*ps)); 79 for(const auto& m:msgs)c.insert(render_message(m)); 80 for(const auto& w:wnds)c.insert(render_window(w)); 81 //] 82 83 //[basic_function_4 84 const char* comma=""; 85 for(const auto& cbk:c){ 86 std::cout<<comma; 87 cbk(std::cout); 88 comma=","; 89 } 90 std::cout<<"\n"; 91 //] 92 93 //[basic_function_5 94 auto cbk=*c.begin(); 95 cbk(std::cout); // renders first element to std::cout 96 std::function<render_callback> f=cbk; 97 f(std::cout); // exactly the same 98 //] 99 100 //[basic_function_6 101 //= *c.begin()=render_message("last minute message"); // compile-time error 102 //] 103 } 104