In addition to the code on how to create objects using the nice C++11 variadic templates (as seen in K-ballo's answer), this answer shows how I would handle a set of classes in a project. This method is a big hack and only recommended if you know what you're doing, however, when adding new classes to your project, you only have to add them to a single file listing all your classes, so if the project gets huge, it helps to keep the overview.
Use this approach only, if you have to list your classes multiple times, for example if you also want to have a std::string className()
function, for example, returning the name of a class without using C++ runtime type information. Every such function which requires to list all classes in your project can be implemented in a similar way than the following.
classes.h
/* For every class in your project which should be creatable through your
* factory, add a line here. */
CLASS(Foo)
CLASS(Bar)
CLASS(Baz)
factory.cpp
template< typename ...Args >
std::shared_ptr<void> createObject( std::string const& name, Args&& ...args )
{
// Define what code to insert for every class:
#define CLASS(T) \
else if(name == #T) \
return std::make_shared<T>(std::forward(args)...);
// List all cases:
if(0) /*do nothing*/; // <-- needed because the macro uses else if
#include "classes.h"
#undef CLASS
return nullptr;
}