This is a mirror of official site: http://jasper-net.blogspot.com/

A Type-safe Generic Pointer

| Sunday, February 20, 2011
Introduction

Sometimes there comes the need to store a pointer to an object whose type is not known at compile-time. The common method to achieve this in C++ is to store it in a void pointer. The void pointer can then be cast back to the appropriate type and used when required. Call-back functions[1] in libraries are a well-known example of this method; the user-data pointer is often a void pointer. This works, but has a glaring problem: it’s not type-safe; it’s up to the programmer to interpret the void pointer in the appropriate manner.

Although programmers are quite used to taking care when dealing with void pointers, every once in a while a void pointer gets accidently cast to the wrong type of object. When this happens, the programmer is actually considered lucky if a crash occurs.

Enter any_ptr

The any_ptr smart pointer[2] can point to any type of object and provide type-safe access to it. In some sense, any_ptr is to pointers what boost::any[3] is to objects. There are no requirements to be fulfilled by the types of objects that any_ptr can point to. In fact, the performance and size penalty incurred by its use is so low, that it could potentially be used almost wherever a void pointer is required.

To start using any_ptr, we simply add a single header any_ptr.h (see source code accompanying this article) to our project. any_ptr has no dependencies on any library and can be used independently. any_ptr also does not require exceptions[5] or RTTI[6] to be enabled.

Type-safety

any_ptr behaves almost like a void pointer, except for when it is type-cast. A cast to the wrong type of pointer will yield a null pointer which the programmer can check for.
Example

int a = 10;
any_ptr pAny = &a;

int   *pA = pAny; // 'pA' will point to 'a'; type-compatible
float *pB = pAny; // 'pB' will point to null; type-incompatible

Const-correctness

any_ptr also takes care of const-correctness[4]; a cast to an incompatible type with respect to const-correctness will yield a null pointer.

Read more: Codeproject

Posted via email from Jasper-net

0 comments: