Cast lambda to std::function with parameter pack

后端 未结 4 929
北海茫月
北海茫月 2021-01-11 17:12

There are several questions on SO that relate to casting lambdas to std::functions, but I have yet to see one that uses a parameter pack for the argument list.

4条回答
  •  太阳男子
    2021-01-11 17:55

    It is very rarely a good idea to cast a lambda to a std::function in a template if you are just going to call it. std::function is type-erasure, and templated type erasure only makes sense if you are going to "pass it on" somewhere else and/or return it.

    In any case, try this:

    template 
    void Functor(std::function f) {}
    
    int main(int argc, char * argv[]) {
      auto x = [] (int a, int b) { return a * b; };
      Functor(x);
      return 0;
    }
    

    but you should really just do

    template 
    void Functor(F f) {}
    

    which is perfectly type-safe.

    If you want early type checking, you could write

    template
    struct signature_compatible;
    template
    struct signature_compatible :
      std::is_consructible< R, std::result_of_t>
    {};
    

    then do

    template 
    void Functor(F f) {
      static_assert( signature_compatible::value, "bad signature" );
    }
    

    but only if you really need to.

提交回复
热议问题