/* Boost.Flyweight example of custom factory. * * Copyright 2006-2008 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/flyweight for library home page. */ /* We include the default components of Boost.Flyweight except the factory, * which will be provided by ourselves. */ #include #include #include #include #include #include #include #include #include using namespace boost::flyweights; /* custom factory based on std::set with some logging capabilities */ /* Entry is the type of the stored objects. Value is the type * on which flyweight operates, that is, the T in flyweoght. It * is guaranteed that Entry implicitly converts to const Value&. * The factory class could accept other template arguments (for * instance, a comparison predicate for the values), we leave it like * that for simplicity. */ template class verbose_factory_class { /* Entry store. Since Entry is implicitly convertible to const Key&, * we can directly use std::less as the comparer for std::set. */ typedef std::set > store_type; store_type store; public: typedef typename store_type::iterator handle_type; handle_type insert(const Entry& x) { /* locate equivalent entry or insert otherwise */ std::pair p=store.insert(x); if(p.second){ /* new entry */ std::cout<<"new: "<<(const Key&)x< accepts it * as such, is by deriving from boost::flyweights::factory_marker. * See the documentation for info on alternative tagging methods. */ struct verbose_factory: factory_marker { template struct apply { typedef verbose_factory_class type; } ; }; /* ready to use it */ typedef flyweight fw_string; int main() { typedef boost::tokenizer > text_tokenizer; std::string text= "I celebrate myself, and sing myself, " "And what I assume you shall assume, " "For every atom belonging to me as good belongs to you. " "I loafe and invite my soul, " "I lean and loafe at my ease observing a spear of summer grass. " "My tongue, every atom of my blood, form'd from this soil, this air, " "Born here of parents born here from parents the same, and their " " parents the same, " "I, now thirty-seven years old in perfect health begin, " "Hoping to cease not till death."; std::vector v; text_tokenizer tok(text,boost::char_separator(" \t\n.,;:!?'\"-")); for(text_tokenizer::iterator it=tok.begin();it!=tok.end();){ v.push_back(fw_string(*it++)); } return 0; }