简体   繁体   English

使用 std::function 存储继承类的方法 c++

[英]Using std::function to store methods of inherited classes c++

Is it possible to do something like this?:有没有可能做这样的事情?:

// 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

And than main.cpp而不是 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");
}

This varriant doesn't work, Cannot create a non-constant pointer to member function So, my question: Is it possible to do smth like that and how?这个变量不起作用,无法创建一个指向成员函数的非常量指针所以,我的问题是:是否有可能像那样做?

You're close: &temp->new_meth isn't valid, you can capture temp into a void() functor through one of these ways:您很接近: &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(); }

Notes:笔记:

  • objects[0] is an invalid index since you never inserted anything into that vector; objects[0]是无效索引,因为您从未在该向量中插入任何内容;
  • objects[0] is a pointer, so you need to dereference it with -> ; objects[0]是一个指针,因此您需要使用->取消引用它;
  • You should use std::unique_ptr instead of raw owning pointers.您应该使用std::unique_ptr而不是原始拥有指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM