any_ptr Class Reference

API: any_ptr Class Reference
API
any_ptr Class Reference

Description

A type-safe equivalent of the void* pointer.

any_ptr accepts a pointer of any type, and keeps the memory address along with the pointer's type. The pointer can be extracted from any_ptr with the exact same type it was used to store it. This was achieved with the use of template methods, typeid() and std::type_info.

The primary use of any_ptr is with cClassDescriptor.

Important: Since std::type_info knows nothing about inheritance relationships, any_ptr cannot perform any upcast or downcast when extracting the pointer.

The following code snippet raises a runtime error:

cMessage *msg = new cMessage();
any_ptr ptr = any_ptr(msg);
cObject *obj = ptr.get<cObject>(); // ==> "Attempt to read any_ptr(cMessage) as cObject*"
The message class in OMNeT++. cMessage objects may represent events, messages, jobs or other entities...
Definition cmessage.h:96
cObject is a lightweight class which serves as the root of the OMNeT++ class hierarchy....
Definition cobject.h:93

When casting is important (~always), the toAnyPtr()/fromAnyPtr() functions should be used for converting an object pointer to and from any_ptr. Most toAnyPtr()/fromAnyPtr() functions are generated by the message compiler from .msg files.

Updated code snippet:

cMessage *msg = new cMessage();
any_ptr ptr = toAnyPtr(msg);
cObject *obj = fromAnyPtr<cObject>(ptr); // works as expected