Boost logo

Boost :

Subject: [boost] [type_factory] new utility/class proposal
From: Vlad Lazarenko (vlad_at_[hidden])
Date: 2011-05-10 19:29:40


Dear Boost developers,

How many times in your experience you needed to associate a type with some identifier known at run-time only? It’s like having an associative container with numeric key and type as a value. Not object, but type. This is a concept similar to object factory pattern but with no objects, only their types. I call it a type factory.

There might be a solution for this in Boost already but I haven’t seen it. Please forgive me if I am just being blind.

Just to give you a little taste of what I mean – imagine that you have a stream of bytes where objects of different types and sizes are stored (serialized), and one byte identifying a type is preceding every such serialized object, and you need to parse it. One approach is to have a switch statement, for example, where all type identifiers are cased, and parse data depending on a type. But then, as list of types grows and/or shrinks, maintenance of this switch becomes unpleasant. And if this logic is in some base library, where user specifies list of types, it becomes even worse. There might be another way, I thought, and came up with sort of hybrid between compile-time types and run-time identifiers – a type factory.

I am wondering if anyone else will find it useful. Perhaps we can have it as part of boost utility classes. Here is a very simple example of usage:

https://github.com/Yocto/type_factory/blob/master/test/simple_example.cpp

It gets a number from “argc”, and then, depending on its value, invokes “speak” method of either “cow”, “dog” or “alligator” classes. More functionality is covered in unit test.

Basically, the type factory, given a list of types as “MPL vector“ is enumerating them from 0 to N. Later, for any given instantiation of “create” method, it generates a dispatch table for invoking of one of template methods (with no arguments) on a supplied “visitor” class.

The source code of the class is here - https://github.com/Yocto/type_factory/blob/master/include/yocto/type_factory.hpp. There are a lot of details, but the main class exposed to the user-land API is “type_factory”.

Please let me know if you are interested in such a concept.

Thank you,

Vlad


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk