Using boost::bind with boost::function: retrieve binded variable type

后端 未结 4 699
自闭症患者
自闭症患者 2020-12-21 04:14

Is there any way to retrieve information on what paramaters were bounded by boost::bind or does this need to be stored manually?

i.e.:

in .h

         


        
4条回答
  •  鱼传尺愫
    2020-12-21 04:57

    As far as I know, you can't do what you want, as std::function throws away (nearly) all type information of the passed function pointer, function object or lambda. It employs a technique called type erasure and on the surface completely forgets what was passed into it, as long as it is callable with the provided arguments. So, after binding, you're out of luck it seems.

    However, you can supply that information yourself:

    #include 
    #include 
    #include 
    #include 
    
    struct call_info{
      std::function func;
      std::string arg_type;
    };
    
    class MyClass{
      std::vector _myVec;
      int _myInt;
      double _myDouble;
    
    public:
      void foo1(int i);
      void foo2(double d);
      void bar();
      void execute(char* param);
    };
    
    void MyClass::bar(){
      call_info info;
      info.func = std::bind(&MyClass::foo1, this, &MyClass::_myInt);
      info.arg_type = "int";
      _myVector.push_back(info);
      info.func = std::bind(&MyClass::foo2, this, &MyClass::_myDouble);
      info.arg_type = "double";
      _myVector.push_back(info);
    }
    
    void MyClass::execute(char* param){
      call_info& info = _myVector[0];
      std::stringstream conv(param);
    
      if(info.arg_type == "int")
        conv >> _myInt;
      else if(info.arg_type == "double")
        conv >> _myDouble;
      info.func();
    }
    

    Not nearly as clean as having it supplied automatically, but as far as I know there's no better way (except completely changing your implementation like sehe proposes).

提交回复
热议问题