Boost learning - An Yi
Boost :: Any - His object, can accommodate any object that meets the type of value (ValueType). J (Who is flicking?)
ValueType requirements:
Code analysis:
Class Any
{
Public: // structors
ANY (): content (0) {}
Template
Any (Const Valuetype & Value): Content (New Holder
ANY (Const any & other): content (other.content? other.content-> clone (): 0) {}
~ any () // Releases Any and All Resources Used in Management Of Instance
{Delete Content;}
Public: // modifier
Any & SWAP (ANY & RHS)
{
Std :: swap (content, rhs.content); // The purpose is to switch the Content pointer
Return * this;
}
Template
Any & Operator = (Const ValueType & RHS)
{
ANY (RHS) .swap (* this);
Return * this;
}
Any & Operator = (Const any & rhs)
{
ANY (RHS) .swap (* this);
Return * this;
}
Public: // queries
BOOL EMPTY () const // true if instance is empty
{
Return! Content; // Learn, learn, so simple code
}
Const st: Type_info & Type () Const
{
RETURN Content? Content-> Type (): TypeId (Void);
}
PUBLIC:
// internal agent class
Class PlaceHolder
{
Public: // structors
Virtual ~ PlaceHolder ()
{
}
Public: // queries
Virtual const st :: type_info & type () const = 0;
Virtual PlaceHolder * Clone () const = 0;
}
Template
Class Holder: Public PlaceHolder
{
Public: // structors
Holder (Const ValueType & Value): Held (Value)
{
}
Public: // queries
Virtual const st :: type_info & type () const
{
Return TypeId (ValyEType);
}
Virtual PlaceHolder * Clone () Const
{
Return New Holder (HELD);
}
Public: // representation
ValueType held; // actual data, it is packaged in two layers.
}
Public: // representation (public so any_cast can be non--friend) PlaceHolder * Content; // Pointer to accommodating valued values
}
Transformation code:
Template
ValueType * Any_cast (any * operand)
{
Return Operand && Operand-> Type () == TypeId (ValyEType)
? & static_cast
(Operand-> Content) -> HELD: 0;
}
Template
Const valuePe * any_cast (const any * operand)
{
Return Any_cast
}
Template
ValueType Any_cast (Const Any & Operand)
{
Const valuePe * result = any_cast
IF (! result)
Throw (BAD_ANY_CAST ());
Return * Result;
}
usefulness:
1:
Under normal circumstances, we can only accommodate a type, or a type inheritance system. Allofed, but can solve this problem by a layer.
Any is all types of trousers, after all types of objects, there is an ANY, and store the ANY type container, which can of course store any objects, not what is internally stored inside the ANY.
2: There is a type left in this world.
Memory layout:
Two types, int, string are shown below.
practical testing:
#include
#include
#include "any.hpp"
Using namespace std;
int main ()
{
String Str ("I Believe I CAN Fly.");
Any Test (STR);
Int T;
Try
{
T = any_cast
}
Catch (Bad_Any_cast & Exp)
{
Std :: cout << Exp.What () << endl;
}
Any INTA (5);
Test.swap (INTA); // // will store the ANY and INT type of the String content. J
Try
{
T = any_cast
}
Catch (Bad_Any_cast & Exp)
{
Std :: cout << Exp.What () << endl;
}
}