Programming

Sunday, April 23, 2006

Opaque library

I've just created a new C++ library called Opaque.

This container can store any C++ datatype in its internal buffer, which can be safely copied and destroyed by code that knows nothing about the type of the stored data.

opaque x = std::string("Hello"), y=x;
x = 2;
assert(x.type() == typeid(int));
std::string &s = y.get<std::string>();
// etc

The container is like Boost.Any, except that it uses an internal buffer to avoid heap allocation. It is similar to Boost.Optional, or Boost.Variant.

Another application is an efficient factory. opaque_ptr is smart "pointer" that can be used to hold derived types. e.g.

class X ...
class Y : public X ...

void factory(opaque_ptr<X> &x)
{
x = Y();
}

opaque_ptr<X> x;
factory(x);

It was inspired by Bronek Kozicki's work on typeless functor.

0 Comments:

Post a Comment

<< Home