Storing member function pointers of derived classes in map - c++

I am trying to implement a factory for two classes Circle, Square both of which inherits from Shape.
class Shape {
public:
virtual static
Shape * getInstance() = 0;
};
class Circle : public Shape {
public:
static const std::string type;
Shape * getInstance() {
return new Circle;
}
};
const std::string Circle::type = "Circle";
class Square : public Shape {
public:
static const std::string type;
Shape * getInstance() {
return new Square;
}
};
const std::string Square::type = "Square";
I want to now create a map with key as shape type (string) and value as a function pointer to getInstance() of the corresponding derived class. Is it possible?
Thanks,
Kiran

Okay I got the mistake.
1) shouldn't declare - virtual static Shape * getInstance() = 0; - in Shape class.
2) getInstance() should be static in all other classes.
Here is the complete implementation
class Shape {
public:
virtual
std::string getType() = 0;
};
class Circle : public Shape {
public:
static const std::string type;
Circle() {
}
std::string getType() {
return type;
}
static
Shape * getInstance() {
return new Circle;
}
};
const std::string Circle::type = "Circle";
class Square : public Shape {
public:
static const std::string type;
Square() {
}
std::string getType() {
return type;
}
static
Shape * getInstance() {
return new Square;
}
};
const std::string Square::type = "Square";
class Triangle : public Shape {
public:
static const std::string type;
Triangle() {
}
std::string getType() {
return type;
}
static
Shape * getInstance() {
return new Triangle;
}
};
const std::string Triangle::type = "Triangle";
typedef Shape * (*getShape)();
typedef std::map<std::string, getShape > factoryMap;
class ShapeFactory {
public:
static factoryMap shapes;
Shape * getInstance(const std::string & type){
factoryMap::iterator itr = shapes.find(type);
if (itr != shapes.end()){
return (*itr->second)();
}
return NULL;
}
};
factoryMap ShapeFactory::shapes;
class ShapeFactoryInitializer {
static ShapeFactoryInitializer si;
public:
ShapeFactoryInitializer() {
ShapeFactory::shapes[Circle::type] = &Circle::getInstance;
ShapeFactory::shapes[Square::type] = &Square::getInstance;
ShapeFactory::shapes[Triangle::type] = &Triangle::getInstance;
}
};
ShapeFactoryInitializer ShapeFactoryInitializer::si;

Although not much relevant to your question, but if you are interested in modern C++ design (factories, smart pointers, etc.), you may like to check this book:
http://www.amazon.co.uk/Modern-Design-Applied-Generic-Patterns/dp/0201704315/ref=sr_1_20?s=books&ie=UTF8&qid=1293359949&sr=1-20
It talk about factories, how to design them, etc.
PS: I am not the author of the book, nor I have been given any thing in return for posting this answer :-)

Change the last line of your code to ShapeFactoryInitializer ShapeFactoryInitializer::si;, then it will pass compilation.

Related

Cannot implement base class with virtual getters that are defined in child classes

I have a class that is called Object, this class's header is:
class DLL_SPEC Object {
public:
Object();
virtual ~Object();
virtual std::string getString() const;
virtual void setString(std::string value);
virtual int getInt() const;
virtual void setInt(int value);
virtual double getDouble() const;
virtual void setDouble(double value);
virtual bool isType(FieldType type) const;
};
And my child classes are as follows:
class DLL_SPEC IntObject : public Object {
public:
IntObject() : value(0) {}
IntObject(int v) : value(v) {}
void setInt(int value) override { this->value = value; };
int getInt() const override { return this->value; };
bool isType(FieldType type) const override;
private:
int value;
};
class DLL_SPEC DoubleObject : public Object {
public:
DoubleObject() : value(0.0) {}
DoubleObject(double v) : value(v) {}
void setDouble(double value) override { this->value = value; };
double getDouble() const override { return this->value; };
bool isType(FieldType type) const override;
private:
double value;
};
class DLL_SPEC StringObject : public Object {
public:
StringObject() : value("") {}
StringObject(std::string v) : value(v) {}
void setString(std::string value) override { this->value = value; };
std::string getString() const override { return value; };
bool isType(FieldType type) const override;
private:
std::string value;
};
Now, the problem is, I have an array of Objects and I want to get a string representation of a StringObject.
I call array[0].getString() and even though the object is of type StringObject, the method that gets called is the one is the base class, which I understand.
So, how would I go about implementing that whenever I call getString() on the base class it goes to the child one of the SAME object?
I've tried using this method:
std::string Object::getString() const
{
return dynamic_cast<StringObject*>(this).getString();
}
but then I get an error stating I cannot cast away const or any type qualifier, which is fixed by deleting const modifier (which I MUST leave there as it's according to the task), but then I get another one stating that no suitable constructor exists. So how would I go about implementing this and getting this base class to use the one of the child one?
EDIT: Added a small example that goes into the getString method of Object class and not the StringObject class.
int findPersonId(std::string whereName)
{
Db* db = Db::open("database");
Table* people = db->openTable("table");
auto iteratorTable = table->select();
while (iteratorTable->moveNext())
{
for (size_t i = 0; i < table->getFieldCount(); i++)
{
if (table->getFields()[i]->getName() == "id")
{ //this one beneath goes to the base class and not StringObject
std::string foundRow = iteratorPeople->getRow()[i]->getString();
if (foundRow == whereName)
{
return iteratorTable->getRowId();
}
}
}
}
return 0;
}
Note: The Table* is 2D array that consists of Object** (array that contains StringObject, IntObject, DoubleObject). The method .getRow() return the Object** array that consists of StringObject ...
The way I initiate the objects that go into the array is
Table* table= db->openOrCreateTable("table", 2, userFields); //this creates a 2d array
StringObject* name = new StringObject("Joseph");
IntObject* id = new IntObject(5);
Object** row = combineToRow(id, name);
table->insert(row); //insert an array into 2D array
The method combineToRow is just a simple convertor to Object**.
template<typename A, typename B>
Object** combineToRow(A a, B b) {
return new Object * [2]{ a, b };
}
You have not implemented a getString method for your IntObject, and since you didn't override it you are calling the base method. Once you implement it like this
class IntObject : public Object {
...
virtual std::string getString() const { return std::to_string(value); };
...
};
then you can call it.
int main(){
StringObject* name = new StringObject("Joseph");
IntObject* id = new IntObject(5);
Object** row = combineToRow(id, name);
std::cout << row[0]->getString() << " " << row[1]->getString();
}
5 Joseph
See working version here

Double dispatch and factory pattern

I've got the following code currently (not working):
#include <iostream>
#include <vector>
class Circle;
class Rectangle;
class Shape {
private:
Shape() {};
public:
virtual ~Shape() {};
friend class Circle;
friend class Rectangle;
};
class Creator {
public:
virtual ~Creator() {};
virtual Shape* create() = 0;
virtual bool equals(Shape& s) { return false; };
};
class Circle : public Shape {
private:
Circle() : Shape() {};
public:
class CircleCreator : public Creator {
public:
virtual Shape* create() { return new Circle(); };
virtual bool equals(Shape& other_shape) { return false; };
};
};
class Rectangle : public Shape {
private:
Rectangle() : Shape() {};
public:
class RectangleCreator : public Creator {
public:
virtual Shape* create() { return new Rectangle(); };
virtual bool equals(Shape& other_shape) { return false; };
};
};
int main() {
/* First step, build the list */
std::vector<Shape*> shapeList;
std::vector<Shape*>::iterator it;
Rectangle::RectangleCreator rc;
Circle::CircleCreator cc;
Shape* s = cc.create();
Shape* s1 = rc.create();
shapeList.push_back(s);
shapeList.push_back(s1);
/* Second step: check if we've got a shape starting from a creator */
for (it = shapeList.begin(); it != shapeList.end(); ++it) {
if (rc.equals(**it)) {
std::cout << "same shape" << std::endl;
}
}
return 0;
}
My goal is to use a factory pattern and avoid the creation of a new object if in a list I've got already that object. I tried to use a double dispatch pattern but it isn't easy to apply in this case. How can I do?
Edit: Since the code is used in a "critical" path, I want to avoid RTTI like dynamic_cast and so on.
Maybe something like this could do it using member variables
#include <iostream>
#include <vector>
enum
{
CIRCLE,
RECTANGLE
};
class Circle;
class Rectangle;
class Shape {
private:
Shape() {};
public:
unsigned shapeType;
virtual ~Shape() {};
friend class Circle;
friend class Rectangle;
};
class Creator {
public:
unsigned shapeType;
virtual ~Creator() {};
virtual Shape* create() = 0;
bool equals(Shape& s) { return (this->shapeType == s.shapeType); };
};
class Circle : public Shape {
private:
Circle() : Shape() {shapeType=CIRCLE;};
public:
class CircleCreator : public Creator {
public:
CircleCreator() {shapeType=CIRCLE;};
virtual Shape* create() { return new Circle(); };
};
};
class Rectangle : public Shape {
private:
Rectangle() : Shape() {shapeType=RECTANGLE;};
public:
class RectangleCreator : public Creator {
public:
RectangleCreator() {shapeType=RECTANGLE;};
virtual Shape* create() { return new Rectangle(); };
};
};
int main() {
/* First step, build the list */
std::vector<Shape*> shapeList;
std::vector<Shape*>::iterator it;
Rectangle::RectangleCreator rc;
Circle::CircleCreator cc;
Shape* s = cc.create();
Shape* s1 = rc.create();
shapeList.push_back(s);
shapeList.push_back(s1);
/* Second step: check if we've got a shape starting from a creator */
for (it = shapeList.begin(); it != shapeList.end(); ++it) {
if (rc.equals(**it)) {
std::cout << "same shape" << std::endl;
}
}
return 0;
}
or this - using virtual function to return type
#include <iostream>
#include <vector>
enum
{
CIRCLE,
RECTANGLE,
UNKNOWN
};
class Circle;
class Rectangle;
class Shape {
private:
Shape() {};
public:
virtual ~Shape() {};
friend class Circle;
friend class Rectangle;
virtual unsigned iAmA(){return UNKNOWN;};
};
class Creator {
public:
virtual ~Creator() {};
virtual Shape* create() = 0;
virtual bool equals(Shape& s) { return false; };
};
class Circle : public Shape {
private:
Circle() : Shape() {};
virtual unsigned iAmA(){return CIRCLE;};
public:
class CircleCreator : public Creator {
public:
CircleCreator() {};
virtual Shape* create() { return new Circle(); };
virtual bool equals(Shape& other_shape) { return (CIRCLE == other_shape.iAmA()); };
};
};
class Rectangle : public Shape {
private:
Rectangle() : Shape() {};
virtual unsigned iAmA(){return RECTANGLE;};
public:
class RectangleCreator : public Creator {
public:
RectangleCreator() {};
virtual Shape* create() { return new Rectangle(); };
virtual bool equals(Shape& other_shape) { return (RECTANGLE == other_shape.iAmA()); };
};
};
int main() {
/* First step, build the list */
std::vector<Shape*> shapeList;
std::vector<Shape*>::iterator it;
Rectangle::RectangleCreator rc;
Circle::CircleCreator cc;
Shape* s = cc.create();
Shape* s1 = rc.create();
shapeList.push_back(s);
shapeList.push_back(s1);
/* Second step: check if we've got a shape starting from a creator */
for (it = shapeList.begin(); it != shapeList.end(); ++it) {
if (rc.equals(**it)) {
std::cout << "same shape" << std::endl;
}
}
return 0;
}
I'm not sure what you're trying to do, but I guess this could point you some direction
enum class Shapes
{
Rectangle,
Circle,
...
};
class Shape
{
private:
Shapes m_shape;
protected:
Shape(Shapes shape)
{
m_shape = shape;
}
public:
Shapes GetShape() { return m_shape; } // this is used to check whether two shapes are equal
virtual ~Shape() = default;
};
And now for factory pattern you'd do:
class ShapeFactory
{
public:
static Shape* CreateShape(Shapes shape)
{
switch (shape)
{
case Shapes::Circle:
return new Circle();
// etc.
}
}
};
This feels very redundant and not very clever to me. Also, this can put alot of code into one place.
For the dispatch, you could do (I assume, I'm not really a fan of this concept as it can be made less verbose with a simple template use)
class ShapeCreator
{
public:
virtual Shape* Create() = 0;
virtual ~ShapeCreator() = default;
};
class Circle : public Shape
{
public:
class Creator : ShapeCreator
{
public:
Shape* Create() { return new Circle(); }
};
Circle() : Shape(Shapes::Circle)
{}
};
bool SomethingWithCircle()
{
Circle::Creator circleCreator;
Shape* first = circleCreator.Create();
Shape* second = circleCreator.Create();
// notice memleak here
return first->GetShape() == second->GetShape();
}
If using C++11, you can go even further and avoid the whole idea /which feels very java-like to me anyway/ using a proper template masturbation techniques. (Can still be applied to pre-C++11, you just won't be able specify the parameters.)
template<class T>
class ShapeCreator
{
public:
template<class... TParams>
static T* Create(TParams&&... parameters) { return new T(std::forward<TParams>(parameters)...); }
};
class Rectangle : public Shape
{
private:
int m_width;
int m_height;
public:
Rectangle(int width, int height) : Shape(Shapes::Rectangle)
{
m_width = width;
m_height = height;
}
};
bool DoSomethingWithRectangles()
{
Rectangle* first = ShapeCreator<Rectangle>::Create(10, 15);
Shape* second = ShapeCreator<Rectangle>::Create(20, 25);
// notice memleak here
return first->GetShape() == second->GetShape();
}
TL;DR
You don't really need RTTI but you need to store the type info somewhere in the base type. I'm using the enum Shapes for this.
Both Factory and Dispatch may seem as a good idea, but you will still need dynamic casting somewhere when using them.
You can replace those two patterns using templates, but as soon as you'll get a vector of the base objects, you'll still have to dynamic_cast at some point.
I didn't measure this whatsoever, but I'm really interested in performance comparison of using virtual functions and dynamic cast as I imagine they'd be very similar...
End note:
Please notice, that I personally feel that using methods like equals or operator== on classes defining the basic interface is not very wise, since there are two possible outcomes:
The equals is virtual -> slow but acceptable
The equals is not virtual -> cannot be used in inherited types to actually do more advanced/relevant comparison, breaking the idea of Open to extension, closed for modification
Obviously, if you don't define the equals, you'd have to write comparison code every time. Or possibly use some templated Comparison class with possible specializations through traits yielding again the best performance with no code duplicity.
Generally speaking, you can get to point where you'd ask yourself "why isn't there base object and reflection like in java or c# in c++? It would allow me to use all these nice and clever patterns." The answer is templates. Why do it run-time, when you can do it compile time?

C++ storing base and derived class objects together

I Have two classes:
First:
class Thing {
public:
int code;
string name;
string description;
int location;
bool canCarry;
Thing(int _code, string _name, string _desc, int _loc, bool _canCarry) {
code = _code;
name = _name;
description = _desc;
location = _loc;
canCarry = _canCarry;
}
};
Second:
class Door: public Thing {
private:
bool open;
public:
int targetLocation;
Door(int _code, string _name, string _desc, int _loc, int _targetLoc) :
Thing(_code, _name, _desc, _loc, false) {
open = false;
targetLocation = _targetLoc;
}
void Use() {
open = true;
}
void Close() {
open = false;
}
bool isOpen() {
return open;
}
};
Forget private/public atributes...
I need to store some objects of base class and some objects of derived class,
something like this:
vector < Thing*> allThings;
things.push_back(new Thing(THING1, "THING1", "some thing", LOC1, true));
things.push_back(new Door(DOOR1, "DOOR1", "some door", LOC1, LOC2));
But in this case, functions Use(), Open(), and isOpen() will not be reachable because of slicing..
Do you have some suggestions, how to store these objects together without creating new structure of vector<Thing*> and vector<Door*>??
Thanks
A good solution to a problem when you need a container of objects with polymorphic behavior is a vector of unique pointers:
std::vector<std::unique_ptr<Thing>>
There would be no slicing in this situation, but you would have to figure out when it's OK to call Use(), Open(), and isOpen().
If you can move the methods from the derived class into the base, go for it; if you cannot do that because it makes no sense for a Thing to have isOpen(), consider using a more advanced solution, such as the Visitor Pattern:
class Thing;
class Door;
struct Visitor {
virtual void visitThing(Thing &t) = 0;
virtual void visitDoor(Door &d) = 0;
};
class Thing {
...
virtual void accept(Visitor &v) {
v.visitThing(*this);
}
};
class Door : public Thing {
...
virtual void accept(Visitor &v) {
v.visitDoor(*this);
}
}
Store pointers instead of instances, and declare public and protected methods as virtual in the base class(es).

Recursive Template idiom how to avoid that the base class is friend of the child classes

I use the recursive template idiom to automatically register all children of a base class in a factory. However in my design the child class must have as a friend class the base class. As the Constructor of my Base class should be private to avoid instantiation of this class other than via the factory.
The overal aim would be that the registration of the factory is done in the BaseSolver and the ChildClasses cannot be instantiated other than via the factory.
Here is the code of my base class which automatically registers all children in the SolverFactory.
template<class T>
struct BaseSolver: AbstractSolver
{
protected:
BaseSolver()
{
reg=reg;//force specialization
}
virtual ~BaseSolver(){}
/**
* create Static constructor.
*/
static AbstractSolver* create()
{
return new T;
}
static bool reg;
/**
* init Registers the class in the Solver Factory
*/
static bool init()
{
SolverFactory::instance().registerType(T::name, BaseSolver::create);
return true;
}
};
template<class T>
bool BaseSolver<T>::reg = BaseSolver<T>::init();
And here the header file of my child class:
class SolverD2Q5 : public BaseSolver<SolverD2Q5>{
private:
//how can I avoid this?
friend class BaseSolver;
SolverD2Q5();
static const std::string name;
}
This works fine. However I really do not like to have to add the BaseSolver as a friend class, however I do not want the constructor and the static member name to be public.
Is there a more elegant solution or a better layout to avoid this?
UPDATE:
I believe the trick has not been understood hence I created the complete solution now. It is just one little change to the code of the OP. Just replace T in the BaseSolver with an empty class definition deriving from T.
Original Text:
I think you can do it by delegating the friendship to a wrapper class that is private to the base Solver. This class will inherit from any class for which instances are to be created. The compiler should optimize the wrapper class away.
#include <iostream>
#include <map>
struct AbstractSolver { virtual double solve() = 0; };
class SolverFactory
{
std::map<char const * const, AbstractSolver * (*)()> creators;
std::map<char const * const, AbstractSolver *> solvers;
public:
static SolverFactory & instance()
{
static SolverFactory x;
return x;
}
void registerType(char const * const name, AbstractSolver *(*create)())
{
creators[name] = create;
}
AbstractSolver * getSolver(char const * const name)
{
auto x = solvers.find(name);
if (x == solvers.end())
{
auto solver = creators[name]();
solvers[name] = solver;
return solver;
}
else
{
return x->second;
}
}
};
template<class T> class BaseSolver : public AbstractSolver
{
struct Wrapper : public T { // This wrapper makes the difference
static char const * const get_name() { return T::name; }
};
protected:
static bool reg;
BaseSolver() {
reg = reg;
}
virtual ~BaseSolver() {}
static T * create() {
return new Wrapper; // Instantiating wrapper instead of T
}
static bool init()
{
SolverFactory::instance().registerType(Wrapper::get_name(), (AbstractSolver * (*)())BaseSolver::create);
return true;
}
};
template<class T>
bool BaseSolver<T>::reg = BaseSolver<T>::init();
struct SolverD2Q5 : public BaseSolver<SolverD2Q5>
{
public:
double solve() { return 1.1; }
protected:
SolverD2Q5() {} // replaced private with protected
static char const * const name;
};
char const * const SolverD2Q5::name = "SolverD2Q5";
struct SolverX : public BaseSolver<SolverX>
{
public:
double solve() { return 2.2; }
protected:
SolverX() {} // replaced private with protected
static char const * const name;
};
char const * const SolverX::name = "SolverX";
int main()
{
std::cout << SolverFactory::instance().getSolver("SolverD2Q5")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverX")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverD2Q5")->solve() << std::endl;
std::cout << SolverFactory::instance().getSolver("SolverX")->solve() << std::endl;
char x;
std::cin >> x;
return 0;
}

c++ defining object type via enum

I have this basic setup:
enum{
BASE,
PRIMITIVE,
...
};
class IUnknown{
public:
bool inline is(int type){return inv_type == type;}
private:
enum {inv_type = BASE};
};
class Primitive: public IUnkown{
private:
enum {inv_type = PRIMITIVE};
};
My problem is that I would want to be able to call is on a Primitive instance and have it return true when type is equal to the value in the enum I have declared in the Primitive class.
The only solution I have found is to declare the 'is' function as virtual and have a copy in every subclass, but I wondered if it would be possible to somehow redefine the enum and have the is function in IUnkown take the value from there
You could have your IUnknown class define a protected constructor (which would then have to be called from each derived class). It would take one of the enum values and store it. The stored value would then be compared against in the is() method.
If you don't like this, and prefer to add a virtual is() method to IUnknown, but don't want to have to define it in every derived class, you could do this:
template <int Tinv_type>
class IUnknownT : public IUnknown{
public:
virtual bool is(int type){return inv_type == type;}
protected:
enum {inv_type = Tinv_type};
};
class Primitive: public IUnknownT<PRIMITIVE>{
};
enums by themselves don't take up storage space because they're just lists of acceptable values for an enum variable. You have to have some runtime storage going on for a virtual function to actually work with the runtime type of the object. I would just use an int or something:
enum{
BASE,
PRIMITIVE,
...
};
class IUnknown{
public:
bool is(int type) const {return inv_type == type;}
protected:
IUnknown(int type) : inv_type(type) { }
private:
const int inv_type;
};
class Primitive: public IUnkown{
private:
Primitive() : IUnknown(PRIMITIVE) { }
};
Why not go all out and use strings instead of enums.
const char * baseStr = "base";
const char * derived1Str = "derived1";
const char * derived2Str = "derived2";
class base
{
public:
virtual bool is(const char * str)
{
return strcmp(baseStr, str) ? false : true;
}
};
class derived1 : public base
{
public:
bool is(const char * str)
{
if ( strcmp(derived1Str, str) )
return base::iA(str);
return true;
}
};
class derived2 : public derived1
{
public:
bool is(const char * str)
{
if ( strcmp(derived2Str, str) )
return derived1::is(str);
return true;
}
};
This has the benefit that this
base * b = new derived2();
bool is = b->isA(baseStr);
sets is to true.