I have a question regarding inheritance with function objects.
I guess this must have been asked a gazzilion times here on Stack Overflow but the sheer number of questions with similar wording makes it near-impossible for me to find anything.
Suppose I have a base abstract class:
class BinaryOperation
{
public:
virtual int operator()(int a, int b) = 0;
};
From which two new classes are derived:
class Plus : public BinaryOperation
{
public:
virtual int operator()(int a, int b)
{
return a + b;
};
};
class Minus : public BinaryOperation
{
public:
virtual int operator()(int a, int b)
{
return a - b;
};
};
I would like to use std::map to map strings to various functors that are derived from the same class:
My first approach was
std::map<std::string, BinaryOperation> operator_map;
operator_map["+"] = Plus();
operator_map["-"] = Minus();
operator_map["-"](5, 2);
Obviously this didn’t work because we cannot instantiate an abstract class.
If I use a pointer to the base class, it works just fine but that looks clumsier and since we have to new the objects that makes it more prone to memory leaks (we have to manually delete the objects)
std::map<std::string, BinaryOperation*> operator_map;
operator_map["+"] = new Plus();
operator_map["-"] = new Minus();
std::cout << (*operator_map["-"])(5, 2)
What would be the preferred way of achieving this functionality without sacrificing the benefits of RAII?
Just make a map of
std::stringtostd::function<int(int, int)>. This allows you to do away with any common base classes, since the function objects provide the polimorphism:Note that the standard library provides functors that implement arithmetic operations in the
functionalheader, so you don’t have to implementMinusandPlusyourself: