Boost::any usage

Source: Internet
Author: User

Boost::any can store any type of C + + type, or it can be a user-defined type. Very convenient, can be very convenient to determine the type of data in the process of operation, so as to carry out related operations.

Function Prototypes:

//In header: <boost/any.hpp>classAny { Public:  //construct/copy/destructany (); Any (ConstAny &); Template<typename valuetype> Any (ConstValueType &); any&operator=(ConstAny &); Template<typename valuetype> Any &operator=(ConstValueType &); ~any (); //modifiersAny & Swap (any &); //Queries  BOOLEmpty ()Const; ConstStd::type_info & Type ()Const;};

member function Description:

The implementation of Boost::any is simple, and any has a template constructor, which allows him to accept any type of object. The real variable content is encapsulated in the member variables of the nested class type, and typeID is used in the nested class to record the true type information.

1) any& swap (any& other); The interchange has values in two any objects.
2) any& operator= (const any& other); If the any instance is not empty, the stored value is discarded and a copy of the other value is deposited.
3) Template<typename valuetype> any& operator= (const valuetype& value); If the any instance is not empty, discard the stored value and deposit it in value Copy, value can be any type that meets any requirement.
4) bool Empty () const, given whether the any instance currently has a value , regardless of the value. Thus, when any holds a pointer, empty also returns false, even if the pointer value is NULL.
5) const- std::type_info& type () const; gives the type of the stored value. If any is empty, the type is void.
6) Any_cast () converts the any type to the true type , and if the pointer returns a null pointer, an exception may be thrown if it is not a pointer.

Three examples

1) Simple instances and calling commonly used member functions:

#include <iostream>#include<string>#include<utility>#include<vector>#include"boost/any.hpp"classA { Public:      voidsome_function () {std::cout<<"a::some_function () \ n"; }};classb{ Public:      voidsome_function () {std::cout<<"b::some_function () \ n"; }};voidPrint_any (boost::any&a) {      if(A * pa=boost::any_cast<a> (& a)) {PA-some_function (); }      Else if(B* pb=boost::any_cast<b> (&a)) {PB-some_function (); }          Else    {           Try{std::cout<< BOOST::ANY_CAST&LT;STD::string> (a) <<'\ n'; }           Catch(boost::bad_any_cast&) {Std::cout<<"oops!\n"; }      }}intMain () {std::cout<<"Example of using any.\n\n"; Std::vector<boost::any>store_anything;      Store_anything.push_back (A ());      Store_anything.push_back (B ()); //we'll come back and add something else .Store_anything.push_back (std::string("This is fantastic!")); Store_anything.push_back (3); Store_anything.push_back (Std::make_pair (true,7.92));     Std::for_each (Store_anything.begin (), Store_anything.end (), print_any); Std::cout<<"Example of using any member functions\n\n"; Boost::any A1 ( -); Boost::any A2 (std::string(" $"));      Boost::any A3; Std::cout<<"A3 is"; if(!A3.empty ()) {Std::cout<<"Not empty\n"; } std::cout<<"empty\n";      A1.swap (A2); Try{std::stringS=BOOST::ANY_CAST&LT;STD::string>(A1); Std::cout<<"A1 contains a string:"<< s <<"\ n"; }      Catch(boost::bad_any_cast&e) {std::cout<<"I guess A1 doesn ' t contain a string!\n"; }      if(int* p=boost::any_cast<int> (&A2)) {Std::cout<<"A2 seems to has swapped contents with A1:"<< *p <<"\ n"; }      Else{std::cout<<"Nope, no int in a2\n"; }       if(typeID (int)==A2.type ()) {Std::cout<<"A2 ' s type_info equals the type_info of int\n"; }} 2resolves a problem similar to map but can be mapped to a variety of different types: #include<iostream>#include<string>#include<vector>#include<algorithm>#include"boost/any.hpp"classproperty{Boost::any Value_; STD::stringname_; Public: Property (ConstSTD::string& Name,Constboost::any&value): name_ (name), Value_ (value) {} std::stringName ()Const{returnname_;} Boost::any& Value () {returnValue_;} FriendBOOL operator< (Constproperty& LHS,Constproperty&RHS) {returnlhs.name_<rhs.name_;}};voidPrint_names (Constproperty&p) {std::cout<< p.name () <<"\ n";}intMain () {std::cout<<"Example of using any for storing properties.\n"; Std::vector<property>properties; Properties.push_back ("B", -)); Properties.push_back ("A", std::string("Thirty something"))); Properties.push_back ("C",3.1415));    Std::sort (Properties.begin (), Properties.end ());    Std::for_each (Properties.begin (), Properties.end (), print_names); Std::cout<<"\ n"; Std::cout<< BOOST::ANY_CAST&LT;STD::string> (properties[0].value ()) <<"\ n"; Std::cout<< boost::any_cast<int> (properties[1].value ()) <<"\ n"; Std::cout<< boost::any_cast<Double> (properties[2].value ()) <<"\ n"; }

Four notes

1) If there is a pointer in any, pay attention to the final release of the pointer, preferably using shared_ptr to manage.
2) If a pointer is in any, if Any.isempty () returns false, the pointer contained by any may still be invalid.
3) If a pointer is in any, no exception will be thrown during the call to Any_cast () conversion, but if it is a generic variable or reference, an incorrect type throws a Boost::bad_any_cast exception.

Five references

1) Beyond the C + + standard Library:an Introduction to Boost
2) Boost online document

Reference: http://www.cppblog.com/mzty/archive/2007/08/16/30156.html

The Any class implements:

The Boost::any class is not a template class, which can greatly facilitate the use of upper-layer applications, which will automate the type conversion. The core is the any class, which contains a base class placeholder pointer to a template class holder, and placeholder is not a template class, so it can be used by any class.

The specifics are as follows:

Http://www.cnblogs.com/wuerping/articles/116414.html

MORE: http://blog.csdn.net/hityct1/article/details/4186962

Boost::any usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.