+1  A: 

Meaning reflection as in Java. there is some info here: http://msdn.microsoft.com/en-us/library/y0114hz2(VS.80).aspx

Generally speaking, search google for "c++ reflection"

Ido
The stuff on the page you refer to is very far from standard c++
anon
+4  A: 

No there isn't. My preferred solution to this problem is to create a dictionary which maps name to creation method. Classes that want to be created like this then register a creation method with the dictionary. This is discussed in some detail in the GoF patterns book.

anon
A: 

This is the factory pattern. See wikipedia (and this example). You cannot create a type per se from a string without some egregious hack. Why do you need this?

dirkgently
I need this because I read the strings from a file, and if I have this, then I can have the factory so generic, that it wouldn't have to know anything in order to create the right instance. This is very powerful.
Gal Goldman
So, are you saying you won't need different class definitions for a Bus and a Car since they are both Vehicles? However, if you do, adding another line shouldn't really be a problem :) The map approach has the same problem -- you update the map contents. The macro thingy works for trivial classes.
dirkgently
I am saying that in order to CREATE a Bus or a Car in my case, I don't need different definitions, otherwise the Factory design pattern would never be in use. My goal was to have the factory as stupid as it can be. But I see here that there's no escape :-)
Gal Goldman
+4  A: 

I have answered in another SO question about C++ factories. Please see there if a flexible factory is of interest. I try to describe an old way from ET++ to use macros which has worked great for me.

ET++ was a project to port old MacApp to C++ and X11. In the effort of it Eric Gamma etc started to think about Design Patterns

epatel
+3  A: 

The short answer is you can't. See these SO questions for why:

  1. Why does C++ not have reflection?
  2. How can I add reflection to a C++ application?
Kristo
+29  A: 

Nope, there is none. You have to do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though:

template<typename T> Base * createInstance() { return new T; }

typedef std::map<std::string, Base*(*)()> map_type;

map_type map;
map["DerivedA"] = &createInstance<DerivedA>;
map["DerivedB"] = &createInstance<DerivedB>;

And then you can do

return map[some_string]();

Getting a new instance. Another idea is to have the types register themself:

// in base.hpp:
template<typename T> Base * createT() { return new T; }

struct BaseFactory {
    typedef std::map<std::string, Base*(*)()> map_type;

    static Base * createInstance(std::string const& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second();
    }

protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map) { map = new map_type; } 
        return map; 
    }

private:
    static map_type * map;
};

template<typename T>
struct DerivedRegister : BaseFactory { 
    DerivedRegister(std::string const& s) { 
        getMap()->insert(std::make_pair(s, &createT<T>));
    }
};

// in derivedb.hpp
class DerivedB {
    ...;
private:
    static DerivedRegister<DerivedB> reg;
};

// in derivedb.cpp:
DerivedRegister<DerivedB> DerivedB::reg("DerivedB");

You could decide to create a macro for the registration

#define REGISTER_DEC_TYPE(NAME) \
    static DerivedRegister<NAME> reg

#define REGISTER_DEF_TYPE(NAME) \
    DerivedRegister<NAME> NAME::reg(#NAME)

I'm sure there are better names for those two though. Another thing which probably makes sense to use here is shared_ptr.

If you have a set of unrelated types that have no common base-class, you can give the function pointer a return type of boost::variant<A, B, C, D, ...> instead. Like if you have a class Foo, Bar and Baz, it looks like this:

typedef boost::variant<Foo, Bar, Baz> variant_type;
template<typename T> variant_type createInstance() { 
    return variant_type(T()); 
}

typedef std::map<std::string, variant_type (*)()> map_type;

A boost::variant is like an union. It knows which type is stored in it by looking what object was used for initializing or assigning to it. Have a look at its documentation here. Finally, the use of a raw function pointer is also a bit oldish. Modern C++ code should be decoupled from specific functions / types. You may want to look into Boost.Function to look for a better way. It would look like this then (the map):

typedef std::map<std::string, boost::function<variant_type()> > map_type;

std::function will be available in the next version of C++ too, including std::shared_ptr.

Johannes Schaub - litb
Loved the idea that the derived classes will register themselves. It's exactly what I was looking for, a way to remove the hard-coded knowledge of which derived classes exist from the factory.
Gal Goldman