Vector of std::function with different signatures

前端 未结 7 1775
离开以前
离开以前 2020-12-03 03:32

I have a number of callback functions with different signatures. Ideally, I would like to put these in a vector and call the appropriate one depending on certain conditions.

7条回答
  •  忘掉有多难
    2020-12-03 04:31

    Direct answer to your question is "NO". Any runtime container would only let you store objects of the same type and std::function<> instantiated with different signatures will be different data types.

    Generally the reason you may want to have "a vector of functions with different signatures" is when you have something like the below (three step processing where input interface is unified (buffer& buf and output interface is unified on_event(Event evt)), but the layer in the middle is heterogeneous process_...(...)

    receive_message(buffer& buf)
      switch(msg_type(buf))
        case A: 
        case B:
        ...
    
    process_A(A& a, One x, Two y)
      ...
      dispatch(Event evt);
      ...
    
    process_B(B& b, Three x);
      ...
      dispatch(Event evt);
      ...
    

    In a solution not involving metaprogramming you'd typically pre-cook a functor doing the end-to-end at initialization time and store those in the vector:

    vector > handlers;
    

提交回复
热议问题