欢迎来到虫虫下载站 | 资源下载 资源专辑 关于我们
虫虫下载站

dynamic_property_map.rst

Boost provides free peer-reviewed portable C++ source libraries. We emphasize libraries that work
RST
字号:
================================|(logo)|__ Dynamic Property Maps================================.. |(logo)| image:: ../../../boost.png   :align: middle   :alt: Boost__ ../../../index.htmSummary-------The dynamic property map interfaces provides access to a collection ofproperty maps through a dynamically-typed interface. An algorithm canuse it to manipulate property maps without knowing their key orvalue types at compile-time. Type-safe codes can use dynamic propertymaps to interface more easily and completely with scripting languagesand other text-based representations of key-value data... contents::Introduction------------The Boost Property Map library specifies statically type-safeinterfaces through which key-value pairs can be manipulated by generic algorithms. Typically, an algorithm that uses property maps isparameterized on the types of the property maps it uses, and itmanipulates them using the interfaces specified by theBoost Property Map Library. The following generic function illustrates property map basics.::  template <typename AgeMap, typename GPAMap>  void   manipulate_freds_info(AgeMap ages, GPAMap gpas) {    typedef typename boost::property_traits<AgeMap>::key_type name_type;    typedef typename boost::property_traits<AgeMap>::value_type age_type;    typedef typename boost::property_traits<GPAMap>::value_type gpa_type;    name_type fred = "Fred";    age_type old_age = get(ages, fred);    gpa_type old_gpa = get(gpas, fred);    std::cout << "Fred's old age: " << old_age << "\n"	      << "Fred's old gpa: " << old_gpa << "\n";    age_type new_age = 18;    gpa_type new_gpa = 3.9;    put(ages, fred, new_age);    put(gpas, fred, new_gpa);  }The function is parameterized on two property map types, ``AgeMap`` and``GPAMap``, and takes a value parameter for each of those types.  Thefunction uses the ``property_traits`` interface to ascertain, atcompile-time, the value and key types of the property maps.  The codethen retrieves Fred's old information, using the ``get`` function, andupdates it using the ``put`` function. The ``get`` function is required by theReadable Property Map concept and both ``get`` and ``put`` are required by theRead/Write Property Map concept.The above function not only requires the two type parameters to modelproperty map concepts, but also makes some extra assumptions.``AgeMap`` and ``GPAMap`` must have the same key type, and that type must beconstructable from a string.  Furthermore, ``AgeMap``'s value type must beconstructable from an ``int``.  Although these requirements are notexplicitly stated, they are statically checked during compilation andfailure to meet them yields compile-time errors.Although the static typing of property map interfaces usually providesdesirable compile-time safety, some algorithms require a more dynamicinterface to property maps. For example, the Boost Graph Library (BGL)provides functions that can initialize a graph by interpreting thecontents of a textual graph description (i.e. a GraphML file).  Suchgeneral-purpose graph description languages can specify an arbitrarynumber of edge and vertex properties, using strings to represent thekey-value pairs.  A graph reader function should capture thesearbitrary properties, but since function templates can only beparameterized on a fixed number of property maps, the traditionaltechniques for handling property maps do not suffice to implement them.Dynamic property maps specifically address the need for an interfaceto property maps whose checking is delayed to runtime.  Severalcomponents combine to provide support for dynamic property maps. The``dynamic_properties`` class collects agroup of heterogenous objects that model concepts fromthe Boost Property Map library. Each property map is assigned astring-based key when it is added to the collection, and it can beaddressed using that key.  Internally, ``dynamic_properties`` adaptseach contained property map with the dynamic property map interface,which provides ``get`` and ``put`` functions thatcan be called using values of any type that meets a few requirements.Internally, the dynamic property map converts key and value pairs tomeet the requirements of the underlying property map or signals aruntime exception if it cannot."Fred's Info" Revisited~~~~~~~~~~~~~~~~~~~~~~~Here's what the example above looks like using the``dynamic_properties`` interface:::  void manipulate_freds_info(boost::dynamic_properties& properties)  {    using boost::get;    std::string fred = "Fred";    int old_age = get<int>("age", properties, fred);    std::string old_gpa = get("gpa", properties, fred);    std::cout << "Fred's old age: " << old_age << "\n"	      << "Fred's old gpa: " << old_gpa << "\n";    std::string new_age = "18";    double new_gpa = 3.9;    put("age",properties,fred,new_age);    put("gpa",properties,fred,new_gpa);  }The new function is not a template parameterized on the property maptypes but instead a concrete function that takes a ``dynamic_properties``object.  Furthermore, the code no longer makes reference to key orvalue types: keys and values are represented with strings.Nonetheless the function still uses non-string types where they areuseful.  For instance, Fred's old age is represented using an ``int``.It's value is retreived by calling ``get`` with atype parameter, which determines its return type.  Finally, the``get`` and ``put`` functions are each supplied a string-based key thatdiffers depending on the property of concern.  Here's an example of how the above function might be called.::  int main()  {    using boost::get;    // build property maps using associative_property_map    std::map<std::string, int> name2age;    std::map<std::string, double> name2gpa;    boost::associative_property_map< std::map<std::string, int> >      age_map(name2age);    boost::associative_property_map< std::map<std::string, double> >      gpa_map(name2gpa);    std::string fred("Fred");    // add key-value information    name2age.insert(make_pair(fred,17));    name2gpa.insert(make_pair(fred,2.7));    // build and populate dynamic interface    boost::dynamic_properties properties;    properties.property("age",age_map);    properties.property("gpa",gpa_map);    manipulate_freds_info(properties);    std::cout << "Fred's age: " << get(age_map,fred) << "\n"	      << "Fred's gpa: " << get(gpa_map,fred) << "\n";	      }The code first creates two property maps using ``std::map`` and the``associative_property_map`` adaptor.  After initializing theproperty maps with key-value data, it constructs a``dynamic_properties`` object and adds to it both property maps,keyed on the strings "age" and "gpa".  Finally ``manipulate_freds_info``is passed the ``dynamic_properties`` object and the results of its changes aredisplayed.  As shown above, the ``dynamic_properties`` object provides, where needed, adynamically-typed interface to property maps yet preserves the statictyping of property map uses elsewhere in an application.Reference---------::  class dynamic_propertiesThe ``dynamic_properties`` class provides a dynamically-typed interface toa set of property maps. To use it, one must populatean object of this class with property maps using the ``property`` memberfunction.Member Functions~~~~~~~~~~~~~~~~::  dynamic_properties()  dynamic_properties(    const boost::function<      std::auto_ptr<dynamic_property_map> (	const std::string&, const boost::any&, const boost::any&)      >& fn)A ``dynamic_properties`` object can be constructed with a function objectthat, when called, creates a new property map.  The library provides the ``ignore_other_properties`` function object, which lets the ``dynamic_properties`` object ignore any properties that it hasn't been prepared to record.If an attempt is madeto ``put`` a key-value pair to a nonexistent ``dynamic_properties`` key,then this function is called with the ``dynamic_properties`` key and theintended property key and value .  If ``dynamic_properties`` isdefault-constructed, such a ``put`` attempt throws ``property_not_found``. ::  template<typename PropertyMap>  dynamic_properties&   property(const std::string& name, PropertyMap property_map)This member function adds a property map to the set of maps contained,using ``name`` as its key.Requirements: ``PropertyMap`` must model Readable Property Map orRead/Write Property Map.::  void insert(const std::string& name, std::auto_ptr<dynamic_property_map> pm)This member function directly adds a ``dynamic_property_map``to the collection, using ``name`` as its key.::  iterator begin()  const_iterator begin() constThis member function returns an iterator over the set of property mapsheld by the ``dynamic_properties`` object.::  iterator end()  const_iterator end() constThis member function returns a terminal iterator over the set ofdynamic property maps held by the ``dynamic_properties`` object.  It is used toterminate traversals over the set of dynamic property maps::  iterator lower_bound(const std::string& name) This member function returns an iterator that points to the firstproperty map whose ``dynamic_properties`` key is ``name``.  Bear in mind that multiple property maps may have the same``dynamic_properties`` key, so long as their property map key types differ.Invariant: The range [ lower_bound(name), end() ) contains everyproperty map that has name for its ``dynamic_properties`` key.Free functions~~~~~~~~~~~~~~::  std::auto_ptr<boost::dynamic_property_map>   ignore_other_properties(const std::string&,                        const boost::any&,                        const boost::any&)When passed to the ``dynamic_properties`` constructor, this functionallows the ``dynamic_properties`` object to disregard attempts to putvalues to unknown keys without signaling an error.::  template<typename Key, typename Value>  bool put(const std::string& name, dynamic_properties& dp, const Key& key,            const Value& value)This function adds a key-value pair to the property map with thematching name and key type. If no matching property map is found,behavior depends on the availability of a property map generator.  Ifa property map generator was supplied when the ``dynamic_properties``object was constructed, then that function is used to create a newproperty map.  If the generator fails to generate a property map(returns a null ``auto_ptr``), then the ``put`` function returns``false``.  If, on the other hand, the ``dynamic_properties`` objecthas no property map generator (meaning it was default-constructed),then ``property_not_found`` is thrown. If a candidate property map isfound but it does not support ``put``, ``dynamic_const_put_error`` isthrown.::  template<typename Value, typename Key>  Value get(const std::string& name, const dynamic_properties& dp,             const Key& key)This function gets the value from the property-map whose namee isgiven and whose key type matches. If ``Value`` is ``std::string``, then theproperty map's value type must either be ``std::string`` or modelOutputStreamable.  In the latter case, the ``get`` function converts thevalue to a string.  If no matching property map is found,``dynamic_get_failure`` is thrown.=============================================================================::  class dynamic_property_mapThis class describes the interface used by ``dynamic_properties`` tointeract with a user's property maps polymorphically. ::  boost::any get(const any& key)Given a representation of a key, return the value associated with that key. Requirement:1) The object passed as the key must be convertible to a value of themap's key type. Details of that conversion are unspecified.2) For this expression to be valid, the key must beassociated with some value, otherwise the result is undefined.::  std::string get_string(const any& key) Given a representation of a key, return the string representationof the value associated with that key.Requirements:1) The object passed as the key must be convertible to theproperty map's key type. Details of that conversion are unspecified.2) For this expression to be valid, the key must beassociated with some value, otherwise the result is undefined.3) The value type of the property map must model Output Streamable.::  void put(const any& key, const any& value) Given a representation of a key and a representation of a value, thekey and value are associated in the property map.Requirements:1) The object passed as the key must be convertible to theproperty map's key type. Details of that conversion are unspecified.2) The object passed as the value must be convertible to theproperty map's value type. Details of that conversion are unspecified.3) The property map need not support this member function, in whichcase an error will be signaled.  This is the runtime analogue of theReadable Property Map concept.::  const std::type_info& key() const Returns a ``type_info`` object that represents the property map's key type.::  const std::type_info& value() const Returns a ``type_info`` object that represents the property map's value type.Exceptions~~~~~~~~~~::  struct dynamic_property_exception : public std::exception {    virtual ~dynamic_property_exception() throw() {}  };  struct property_not_found : public std::exception {    std::string property;    property_not_found(const std::string& property);    virtual ~property_not_found() throw();    const char* what() const throw();  };  struct dynamic_get_failure : public std::exception {    std::string property;    dynamic_get_failure(const std::string& property);    virtual ~dynamic_get_failure() throw();    const char* what() const throw();  };  struct dynamic_const_put_error  : public std::exception {    virtual ~dynamic_const_put_error() throw();    const char* what() const throw();  };Under certain circumstances, calls to ``dynamic_properties`` memberfunctions will throw one of the above exceptions.  The three concreteexceptions can all be caught using the general``dynamic_property_exception`` moniker when greater precision is notneeded.  In addition, all of the above exceptions derive from thestandard ``std::exception`` for even more generalized error handling.The specific circumstances that result in these exceptions aredescribed above.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -