Boost logo

Boost :

From: Roland Schwarz (roland.schwarz_at_[hidden])
Date: 2004-12-05 09:57:35


As a byproduct of my current work I factored out a small utility
library that implements a virtual constructor.

The implementation is based on boost::any and typeid(...).name().
It features dynamic creation of objects by name (string), and allows
for default and custom constructors beeing called.

It could be used as the basic step to object deserialization from
a file, creation of operating system dependent implementations,
or allow a library to instantiate user-pluggable classes.

The design is inspired by the Io_obj example from Stroustrup's book
on C++ programming.

A small example to show the usage:

#include <string>
#include <iostream>
#include "dynanew.hpp"

using namespace dynanew;

// a simple class hierarchy with abstact base class
struct shape {
    virtual void draw() = 0;
};

struct square : public shape {
    virtual void draw() {
        std::cout << "I am a square" << std::endl;
    }
};

struct circle : public shape {
    circle() : radius(0) {}
    circle(double dr) : radius(dr) {}
    virtual void draw() {
        std::cout << "I am a circle of radius: " << radius << std::endl;
    }
    double radius;
};

// create the type map
TYPE_MAP(shape);
// square with default constructor
TYPE_REGISTER(shape, square);
// circle with custom constructor taking a double parameter
TYPE_REGISTER1(shape, circle, double);
// circle with default constructor
TYPE_REGISTER(shape, circle);
 
int main(int argc, char* argv[])
{
    std::string type;
    type = "square";
    shape* ps1 = dynamic_new<shape>(type);
    shape* ps2 = dynamic_new<shape>("circle", 20.0);
    shape* ps3 = dynamic_new<shape>("circle");
    shape* ps4 = dynamic_new<shape>("square", 10.0);

    if (ps1) ps1->draw(); // prints: I am a square
    if (ps2) ps2->draw(); // prints: I am a circle of radius: 20.0
    if (ps3) ps3->draw(); // prints: I am a circle of radius: 0.0
    if (ps4) ps4->draw(); // does nothing since no ctor available

    delete ps1;
    delete ps2;
    delete ps3;
    delete ps4;

    return 0;
}

regards,
Roland


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