按名称调用父级中的子类方法
Call child class method in parent by name
如何实现invoke
函数?
class Args {};
class NoSuchMethod {};
class Base {
public:
Args invoke(std::string name, Args a) {
//get method and call it or
//throw NoSuchMethod()
}
};
class One: public Base {
int q;
public:
One(int q_): q(q_) {};
Args test(Args a) {
printf("One::test() -> q = %d", q);
};
};
class Two: public Base {
std::string s;
public:
Two(std::string s_): s(s_) {};
Args test2(Args a) {
printf("Two::test2() -> t = %s", s.c_str());
};
};
std::vector<Base*> objs = {new One(123), new One(321), new Two("ha"), new One(0)};
int main() {
objs[0]->invoke("test", Args());
objs[1]->invoke("test", Args());
objs[2]->invoke("test2", Args());
objs[3]->invoke("test", Args());
}
不能直接从字符串调用方法。 如果基方法无权访问父方法的类型,则也无法从基方法调用父方法。
实现此目的的一种方法是设置一个包含所需功能的映射。
类似的东西(代码未编译,但它应该给你一个想法(:
class Base {
public:
Args invoke(std::string name, Args a) {
auto foundMethod = methods_.find(name);
if (foundMethod == methods_.end())
{
throw NoSuchMethod();
}
(*foundMethod)(a);
}
protected:
std::map<std::string, std::function<void(Args)>> methods_;
};
class One: public Base {
int q;
public:
One(int q_): q(q_)
{
methods_["test"] = std::bind(&One::test, this, std::placeholders::_1);
};
Args test(Args a) {
printf("One::test() -> q = %d", q);
};
};
class Two: public Base {
std::string s;
public:
Two(std::string s_): s(s_)
{
methods_["test2"] = std::bind(&Two::test, this, std::placeholders::_1);
};
Args test2(Args a) {
printf("Two::test2() -> t = %s", s.c_str());
};
};
相关文章:
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 从基类实例调用派生类方法而不进行强制转换
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 函数从唯一代码调用正确的子类方法
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- C++:从属性类调用顶级类方法
- 指向类方法调用的指针
- 有没有办法从同一类中的函子调用类方法?
- 有没有办法禁止派生类中的基类方法调用?
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- 我可以从析构函数的类方法调用它吗
- C++指向类方法调用的指针
- 基类方法调用派生类方法,任何可能的解决方案
- 从基类方法调用虚拟方法
- 非常具体的子类方法调用
- 类方法调用是否会在for循环中进行优化
- 使用具有相同声明的类方法调用全局函数
- 如何在c++中实现抽象类,同时允许子类方法调用