template argument deduction/substitution failed, when using std::function and std::bind

后端 未结 2 360
傲寒
傲寒 2020-12-30 21:32

I have a compile error when using std::function in a templated member function, the following code is a simple example:

#include 
#include          


        
相关标签:
2条回答
  • 2020-12-30 22:06

    You can make type deduction work with some variant of:

    template<typename CALLBACK>
    void setCallback(CALLBACK cb) {
      typedef CALLBACK::first_argument_type T;
      static_assert(is_same_type<CALLBACK,function<void(T,int)>>::value);
      ...
    }
    

    This way CALLBACK can be determined by looking at the argument. It might get into trouble if bind doesn't actually return a std::function but rather something that can be cast as one. I'm not sure.

    0 讨论(0)
  • 2020-12-30 22:16

    To figure out the problem let separate statements:

    auto f = bind(&TestA::testa, &testA, _1, _2); // OK
    test.setCallback(f);                          // <<--- Error is here
    

    setCallback needs to know type of T and it can't deduce it from f, so give it a type

    test.setCallback<TYPE>(f); // TYPE: int, float, a class, ...
    
    0 讨论(0)
提交回复
热议问题