Aphex_Twin
Evergreen
- Joined
- Sep 7, 2002
- Messages
- 7,474
I'm trying to find a little C++ help fast. If you are up to it, take a look below...
I'm wrestling with generalizing object factories. I seem to not be able to insert function pointers into stl maps.
My compiler gives off a few errors, primarily due to this line:
std::map<KeyType, (*ObjectType)()> registry;
I'm wrestling with generalizing object factories. I seem to not be able to insert function pointers into stl maps.
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;
}
My compiler gives off a few errors, primarily due to this line:
std::map<KeyType, (*ObjectType)()> registry;