|
Who ever said C++ was an easy language to learn must probably be insane or a genius (or probably both). I have a few issues with a thing called "object factory". Here is my code:
[code]#include <iostream>
#include <map>
template <class ObjectType, class KeyType>
class Factory
{
public:
Factory () {registry.empty(); }
ObjectType* Create (KeyType name)
{
std::map<KeyType, (*ObjectType)()>::iterator i;
i=registry.find((KeyType)name);
return *i();
}
bool Register (KeyType name, ObjectType* (*CreatorFunction)())
{
if (!IsRegistered(name))
{
registry[name] = CreatorFunction;
return true;
}
return false;
}
bool UnRegister (KeyType name, ObjectType* (*CreatorFunction)())
{
if (!IsRegistered(name))
{
registry.erase ((KeyType)name);
return true;
}
return false;
}
bool IsRegistered (KeyType name)
{
std::map<KeyType, (*ObjectType)()>::iterator i;
i = registry.find ((KeyType)name);
if (i != registry.end())
return true;
else
return false;
}
private:
std::map<KeyType, (*ObjectType)()> registry;
};
class Shape
{
public:
virtual void Rotate()=0;
virtual void Translate()=0;
};
class Circle: public Shape
{
public:
int x, y, z;
void some_func (void) { std::cout << "Test!"; }
void Rotate () { std::cout <<"Rotating circle\n"; }
void Translate () { std::cout << "Translating circle\n";; }
};
Shape* CircleCreate (void) { return new Circle; }
class Triangle: public Shape
{
public:
int x1, y1, x2, y2, x3, y3;
void Rotate () { std::cout <<"Rotating triangle\n"; }
void Translate () { std::cout << "Translating triangle\n"; }
};
Shape* TriangleCreate (void) { return new Triangle; }
class Square: public Shape
{
public:
int x1, y1, x2, y2, l;
void Rotate () { std::cout <<"Rotating square\n"; }
void Translate () { std::cout << "Translating square\n"; }
};
Shape* SquareCreate (void) { return new Square; }
int main(int argc, char *argv[])
{
Factory<std::string, Shape> factory;
Shape *s;
factory.Register ("triangle", TriangleCreate);
factory.Register ("square", SquareCreate);
factory.Register ("circle", CircleCreate);
s = factory.Create("triangle");
s->Rotate();
return EXIT_SUCCESS;
}[/code]
The attempt to generalize the Factory class seems to fail.
My compiler gives off a few errors, primarily due to this line: std::map<KeyType, (*ObjectType)()> registry;
I want to register a pointer to a function that returns an "ObjectType" in a stl map. Just one "pointer" in the right direction is all that I need. :)
<Added>
VBscript doesn't seem to work with this forum. Here is a readable link to the source:
http://aphextwin.goldeye.info/source.txt
|
|
|
|
|
|
|
|