tags:

views:

1572

answers:

6

Hi,

imagine I have a bunch of C++ related classes (all extending the same base class and providing the same constructor) that I declared in a common header file (which I include), and their implementations in some other files (which I compile and link statically as part of the build of my program).

I would like to be able to instantiate one of them passing the name, which is a parameter that has to be passed to my program (either as command line or as a compilation macro).

The only possible solution I see is to use a macro:

#ifndef CLASS_NAME
#define CLASS_NAME MyDefaultClassToUse
#endif

BaseClass* o = new CLASS_NAME(param1, param2, ..);

Is it the only valuable approach?

+2  A: 

In C++, this decision must be made at compile time.

During compile time you could use a typedef rather than a macor:

typedef DefaultClass MyDefaultClassToUse;

this is equivalent and avoids a macro (macros bad ;-)).

If the decision is to be made during run time, you need to write your own code to support it. The simples solution is a function that tests the string and instantiates the respective class.

An extended version of that (allowing independent code sections to register their classes) would be a map<name, factory function pointer>.

peterchen
"An extended version of that (allowing independent code sections to register their classes) would be a map<name, factory function pointer>."would it be possible, from a class definition, to register itself into that map, assuming this map is in a Factory elsewhere?In Java I could/would do it using static{} constructors. In fact I don't want for each new sub-class that I write, to modify the code of the Factory.
puccio
+2  A: 

Why not use an object factory?

In its simplest form:

BaseClass* myFactory(std::string const& classname, params...)
{
    if(classname == "Class1"){
        return new Class1(params...);
    }else if(...){
        return new ...;
    }else{
       //Throw or return null
    }
    return NULL;
}
mandrake
+13  A: 

This is a problem which is commonly solved using the Registry Pattern:

This is the situation that the Registry Pattern describes:

Objects need to contact another object, knowing only the object’s name or the name of the service it provides, but not how to contact it. Provide a service that takes the name of an object, service or role and returns a remote proxy that encapsulates the knowledge of how to contact the named object.

It’s the same basic publish/find model that forms the basis of a Service Oriented Architecture (SOA) and for the services layer in OSGi.

You implement a registry normally using a singleton object, the singleton object is informed at compile time or at startup time the names of the objects, and the way to construct them. Then you can use it to create the object on demand.

For example:

template<class T>
class Registry
{
    typedef boost::function0<T *> Creator;
    typedef std::map<std::string, Creator> Creators;
    Creators _creators;

  public:
    void register(const std::string &className, const Creator &creator);
    T *create(const std::string &className);
}

You register the names of the objects and the creation functions like so:

Registry<I> registry;
registry.register("MyClass", &MyClass::Creator);

std::auto_ptr<T> myT(registry.create("MyClass"));

We might then simplify this with clever macros to enable it to be done at compile time. ATL uses the Registry Pattern for CoClasses which can be created at runtime by name - the registration is as simple as using something like the following code:

OBJECT_ENTRY_AUTO(someClassID, SomeClassName);

This macro is placed in your header file somewhere, magic causes it to be registered with the singleton at the time the COM server is started.

1800 INFORMATION
+1  A: 

You mention two possibilities - Command line and compilation macro but the solution for the each one is vastly different.

If the choice is made by a compilation macro than it's a simple problem which can be solved with #defines and #ifdefs and the like. The solution you propose is as good as any.

But if the choice is made in run-time using a command line argument then you need to have some Factory framework that is able to receive a string and create the appropriate object. This can be done using a simple, static if().. else if()... else if()... chain that has all the possibilities or can be a fully dynamic framework where objects register and are being cloned to provide new instances of themselves.

shoosh
+1  A: 

A way to implement this is hard-coding a mapping from class 'names' to a factory function. Templates may make the code shorter. The STL may make the coding easier.

#include "BaseObject.h"
#include "CommonClasses.h"

template< typename T > BaseObject* fCreate( int param1, bool param2 ) {
    return new T( param1, param2 );
}

typedef BaseObject* (*tConstructor)( int param1, bool param2 );
struct Mapping { string classname; tConstructor constructor; 
    pair<string,tConstructor> makepair()const { 
        return make_pair( classname, constructor ); 
    }
} mapping[] = 
{ { "class1", &fCreate<Class1> }
, { "class2", &fCreate<Class2> }
// , ...
};

map< string, constructor > constructors;
transform( mapping, mapping+_countof(mapping), 
    inserter( constructors, constructors.begin() ), 
    mem_fun_ref( &Mapping::makepair ) );
xtofl
Yeargs, the 'transform' call at the end makes my eyes hurt. %-)
Frerich Raabe
You're right. You can also _not_ use a map and find the proper constructor with a loop.
xtofl
A: 

In the past, I've implemented the Factory pattern in such a way that classes can self-register at runtime without the factory itself having to know specifically about them. The key is to use a non-standard compiler feature called (IIRC) "attachment by initialisation", wherein you declare a dummy static variable in the implementation file for each class (e.g. a bool), and initialise it with a call to the registration routine.

In this scheme, each class has to #include the header containing its factory, but the factory knows about nothing except the interface class. You can literally add or remove implementation classes from your build, and recompile with no code changes.

The catch is that only some compilers support attachment by initialisation - IIRC others initialise file-scope variables on first use (the same way function-local statics work), which is no help here since the dummy variable is never accessed and the factory map will always be found empty.

The compilers I'm interested in (MSVC and GCC) do support this, though, so it's not a problem for me. You'll have to decide for yourself whether this solution suits you.