调用派生类的函数调用运算符时避免使用指针
Avoiding pointers when calling the function call operator of the derived class
我有一个关于函数对象继承的问题。
我想这肯定是在 Stack Overflow 上问了太多次的,但措辞相似的问题数量之多使我几乎不可能找到任何东西。
假设我有一个基本的抽象类:
class BinaryOperation
{
public:
virtual int operator()(int a, int b) = 0;
};
从中派生出两个新类:
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;
};
};
我想使用 std::map
将字符串映射到派生自同一类的各种函子:
我的第一个方法是
std::map<std::string, BinaryOperation> operator_map;
operator_map["+"] = Plus();
operator_map["-"] = Minus();
operator_map["-"](5, 2);
显然,这不起作用,因为我们不能实例化抽象类。
如果我使用指向基类的指针,它可以正常工作,但看起来更笨拙,并且由于我们必须new
对象,这使得它更容易发生内存泄漏(我们必须手动delete
对象)
std::map<std::string, BinaryOperation*> operator_map;
operator_map["+"] = new Plus();
operator_map["-"] = new Minus();
std::cout << (*operator_map["-"])(5, 2)
在不牺牲 RAII 优势的情况下实现此功能的首选方法是什么?
只需制作一张std::string
到std::function<int(int, int)>
的地图。这允许您取消任何公共基类,因为函数对象提供多态性:
struct Plus {
int operator()(int a, int b) const{ return a+b; }
};
struct Minus {
int operator()(int a, int b) const{ return a-b; }
};
int main()
{
std::map<std::string, std::function<int(int,int)>> opMap;
using namespace std::placeholders;
opMap["-"] = Minus();
opMap["+"] = Plus();
std::cout << opMap["-"](5,2) << std::endl;
std::cout << opMap["+"](5,6) << std::endl;
}
请注意,标准库提供了在 functional
标头中实现算术运算的函子,因此您不必自己实现Minus
和Plus
:
opMap["-"] = std::minus<int>();
opMap["+"] = std::plus<int>();
相关文章:
- C++ 带有函数指针的运算符优先级
- 是否允许编译器省略对指针的 &* 运算符的组合调用?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 在一个指令中声明更多指针的运算符优先级
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- c++:复制、删除和运算符=在原始指针映射中
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- 类重载运算符 '<' 插入指向该对象集的共享指针时不调用
- 使用继承的指针列表复制构造函数或重载运算符=
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- Caffe 源代码中层函数标头中指针运算符的含义
- 嵌套智能指针运算符>
- 运算符和指针运算符的地址
- 对于什么对象指针值,指向成员的指针运算符调用未定义的行为
- 在 65536 位置访问迭代器的指针运算符会导致段错误
- 检测对堆栈变量的调用delete(使用强制转换到指针运算符)
- C++中指向成员的指针运算符 ->* 和 .* 是什么?
- 关于智能指针运算符*和运算符>重载的说明