basic_any.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /* basic usage of boost::any_collection */
  9. #include <boost/poly_collection/any_collection.hpp>
  10. #include <boost/type_erasure/operators.hpp>
  11. #include <random>
  12. #include "rolegame.hpp"
  13. //[basic_any_1
  14. std::ostream& operator<<(std::ostream& os,const sprite& s)
  15. {
  16. s.render(os);
  17. return os;
  18. }
  19. // std::string already has a suitable operator<<
  20. std::ostream& operator<<(std::ostream& os,const window& w)
  21. {
  22. w.display(os);
  23. return os;
  24. }
  25. //]
  26. int main()
  27. {
  28. //[basic_any_2
  29. //= #include <boost/poly_collection/any_collection.hpp>
  30. //= #include <boost/type_erasure/operators.hpp>
  31. //= ...
  32. //=
  33. using renderable=boost::type_erasure::ostreamable<>;
  34. boost::any_collection<renderable> c;
  35. //]
  36. //[basic_any_3
  37. // populate with sprites
  38. std::mt19937 gen{92748}; // some arbitrary random seed
  39. std::discrete_distribution<> rnd{{1,1,1}};
  40. for(int i=0;i<4;++i){ // assign each type with 1/3 probability
  41. switch(rnd(gen)){
  42. case 0: c.insert(warrior{i});break;
  43. case 1: c.insert(juggernaut{i});break;
  44. case 2: c.insert(goblin{i});break;
  45. }
  46. }
  47. // populate with messages
  48. c.insert(std::string{"\"stamina: 10,000\""});
  49. c.insert(std::string{"\"game over\""});
  50. // populate with windows
  51. c.insert(window{"pop-up 1"});
  52. c.insert(window{"pop-up 2"});
  53. //]
  54. //[basic_any_4
  55. const char* comma="";
  56. for(const auto& r:c){
  57. std::cout<<comma<<r;
  58. comma=",";
  59. }
  60. std::cout<<"\n";
  61. //]
  62. }