[英]Using std::function to store methods of inherited classes c++
有沒有可能做這樣的事情?:
// some_header.hpp
#ifndef SOME_HEADER_HPP
#define SOME_HEADER_HPP
class baseclass
{
public:
baseclass(){};
std::map<std::string, std::function<void()>> methods_map;
void call_method(const std::string &name){
auto it = methods_map.find(name);
if(it != methods_map.end())
it->second();
else std::cout << "Method " << name << " not exists";
}
};
#endif
而不是 main.cpp
#include "some_header.hpp"
class inherited : public baseclass{
public:
inherited():baseclass(){};
void new_meth(){
std::cout << "Hello, stackoverflow!";
}
};
int main(){
std::vector<baseclass*> objects;
auto temp = new inherited();
objects[0].methods_map["new"]=&temp->new_meth;
objects[0].call_method("new");
}
這個變量不起作用,無法創建一個指向成員函數的非常量指針所以,我的問題是:是否有可能像那樣做?
您很接近: &temp->new_meth
無效,您可以通過以下方式之一將temp
捕獲到void()
函子中:
objects[0]->methods_map["new"] = std::bind_front(&inherited::new_meth, temp);
objects[0]->methods_map["new"] = [&] { return temp->new_meth(); }
筆記:
objects[0]
是無效索引,因為您從未在該向量中插入任何內容;objects[0]
是一個指針,因此您需要使用->
取消引用它;std::unique_ptr
而不是原始擁有指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.