将函数指针插入到具有多态返回类型的映射中
Insert function pointer into map with polymorphic return type
我不知道如何为这个问题命名。我有一个基类和两个继承类:
class Base {};
class Action : public Base {};
class Title : public Base {};
现在假设我有两个返回 Action *
或 Title *
的函数:
Action *getAction() { return new Action; }
Title *getTitle() { return new Title; }
有没有办法把这两个函数放到地图里?这样:
int main()
{
std::map<std::string, Base *(*)()> myMap;
myMap["action"] = getAction;
myMap["title"] = getTitle;
return 0;
}
现在我收到一个错误:
invalid conversion from `Action* (*)()' to `Base* (*)()'
我可以更改函数的签名以始终返回基类,然后它就可以工作,但我想知道是否有另一种方法可以解决这个问题。
如果您使用:
Base *getAction() { return static_cast<Base *>(new Action); }
Base *getTitle() { return static_cast<Base *>(new Title); }
那么你不会得到这个错误。
std::function
是由 STL 提供的多态函数指针包装器。
当然,使用模板,您可以编写自己的函数包装器来存储目标、传递前向参数并进行转换。不过,这已经完成了,在决定自己推出之前,您应该认真考虑。除非您喜欢重新发明轮子或有非常特殊的要求。
作为概念证明,我有以下代码:
#include <iostream>
#include <map>
#include <functional>
struct A
{
virtual void f() = 0;
};
struct B : public A
{
void f() { std::cout << "B::fn"; }
};
struct C : public A
{
void f() { std::cout << "C::fn"; }
};
B* getB() { return new B; }
C* getC() { return new C; }
int main()
{
std::map<std::string, std::function<A*()>> m;
m["b"] = getB;
m["c"] = getC;
m["b"]()->f();
m["c"]()->f();
}
它泄漏内存,但它有效。
相关文章:
- 通过switch和static_cast访问多态对象的运行时类型
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 如何调用指针类型的方法(禁用多态性)?
- 如何在不同类型的值之间进行选择以传递给多态函数?
- C++ 多态模板类,模板类型对象的实例化
- 如何多态地使用替代类型的 std::变体
- 将unique_ptr返回到多态类型
- 将函数指针插入到具有多态返回类型的映射中
- 返回不带动态内存分配的多态类型
- 多态性不适用于相同数据类型(Base和Inherited类)的函数返回值
- 是否可以找出多态C++ 14 lambda 的参数类型和返回类型
- C++多态性:虚拟方法的返回类型
- C++多态性+用于选择返回类型的模板成员函数.如何做到这一点
- C++中的多态返回类型
- C++中具有多态模板类的未知方法返回类型
- 具有不同返回类型的C++多态函数
- 如何在C++中创建一个工厂方法,允许以多态方式返回不同的类型
- 返回与定义的多态函数不同的类型