key_value.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* Boost.Flyweight example of use of key-value flyweights.
  2. *
  3. * Copyright 2006-2008 Joaquin M Lopez Munoz.
  4. * Distributed under the Boost Software License, Version 1.0.
  5. * (See accompanying file LICENSE_1_0.txt or copy at
  6. * http://www.boost.org/LICENSE_1_0.txt)
  7. *
  8. * See http://www.boost.org/libs/flyweight for library home page.
  9. */
  10. #include <boost/array.hpp>
  11. #include <boost/flyweight.hpp>
  12. #include <boost/flyweight/key_value.hpp>
  13. #include <cstdlib>
  14. #include <iostream>
  15. #include <string>
  16. #include <vector>
  17. using namespace boost::flyweights;
  18. /* A class simulating a texture resource loaded from file */
  19. class texture
  20. {
  21. public:
  22. texture(const std::string& filename):filename(filename)
  23. {
  24. std::cout<<"loaded "<<filename<<" file"<<std::endl;
  25. }
  26. texture(const texture& x):filename(x.filename)
  27. {
  28. std::cout<<"texture["<<filename<<"] copied"<<std::endl;
  29. }
  30. ~texture()
  31. {
  32. std::cout<<"unloaded "<<filename<<std::endl;
  33. }
  34. const std::string& get_filename()const{return filename;}
  35. // rest of the interface
  36. private:
  37. std::string filename;
  38. };
  39. /* key extractor of filename strings from textures */
  40. struct texture_filename_extractor
  41. {
  42. const std::string& operator()(const texture& x)const
  43. {
  44. return x.get_filename();
  45. }
  46. };
  47. /* texture flyweight */
  48. typedef flyweight<
  49. key_value<std::string,texture,texture_filename_extractor>
  50. > texture_flyweight;
  51. int main()
  52. {
  53. /* texture filenames */
  54. const char* texture_filenames[]={
  55. "grass.texture","sand.texture","water.texture","wood.texture",
  56. "granite.texture","cotton.texture","concrete.texture","carpet.texture"
  57. };
  58. const int num_texture_filenames=
  59. sizeof(texture_filenames)/sizeof(texture_filenames[0]);
  60. /* create a massive vector of textures */
  61. std::cout<<"creating flyweights...\n"<<std::endl;
  62. std::vector<texture_flyweight> textures;
  63. for(int i=0;i<50000;++i){
  64. textures.push_back(
  65. texture_flyweight(texture_filenames[std::rand()%num_texture_filenames]));
  66. }
  67. /* Just for the sake of making use of the key extractor,
  68. * assign some flyweights with texture objects rather than strings.
  69. */
  70. for(int j=0;j<50000;++j){
  71. textures.push_back(
  72. texture_flyweight(
  73. textures[std::rand()%textures.size()].get()));
  74. }
  75. std::cout<<"\n"<<textures.size()<<" flyweights created\n"<<std::endl;
  76. return 0;
  77. }