Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Developing U++ » U++ Developers corner » Template class factory
Re: Template class factory [message #24383 is a reply to message #24382] Wed, 13 January 2010 11:40 Go to previous messageGo to previous message
mdelfede is currently offline  mdelfede
Messages: 1307
Registered: September 2007
Ultimate Contributor
A better version with RTTI class identification :

#ifndef _ClassFactory_ClassFactory_h_
#define _ClassFactory_ClassFactory_h_

#include <Core/Core.h>
using namespace Upp;

template<class T> class WithFactory
{
	private:
		typedef One<T> (*CreateFunc)();
		typedef VectorMap<String, CreateFunc>mapType;
		static mapType &classMap() { static mapType cMap; return cMap; }
		template<class D> static One<T> __Create(void) { return One<T>((T *)new D); }
		String myType;
	public:
	
		template<class D> static void Register(const String &name) { classMap().Add(name, __Create<D>); }
		static One<T> Create(const String &className)
		{
			One<T> me = classMap().Get(className)();
			me->myType = className;
			return me;
		}
		static Vector<String> const &Classes(void) { return classMap().GetKeys(); }
		String const &IsA(void) { return myType; }
};

#define REGISTERCLASS(type) \
	INITBLOCK { \
	type::Register<type>(#type); \
}
#endif


Usage :

#include "ClassFactory.h"

class Base : public WithFactory<Base>
{
};

class Derived : public Base
{
};

REGISTERCLASS(Base);
REGISTERCLASS(Derived);

CONSOLE_APP_MAIN
{
	One<Base> p1 = Base::Create("Base");
	One<Base> p2 = Base::Create("Derived");

	Cerr() << "p1 is a '" << p1->IsA() << "'\n";
	Cerr() << "p2 is a '" << p2->IsA() << "'\n";
	
}


Now classes knows themselves Smile

Ciao

Max

[Updated on: Wed, 13 January 2010 12:22]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Helper for internazionalize arrays of literals
Next Topic: Polymorphic XMLizer
Goto Forum:
  


Current Time: Fri May 10 02:53:52 CEST 2024

Total time taken to generate the page: 0.02480 seconds