Lambda is deduced to std::function if template has no variadic arguments

前端 未结 2 1397
有刺的猬
有刺的猬 2021-02-07 22:08
template
void foo(std::function callback)
{}

template
voi         


        
相关标签:
2条回答
  • 2021-02-07 22:29
    template<typename ReturnT, typename... ParamT>
    void foo(std::function<ReturnT(ParamT...)> callback)
    {}
    

    now, foo<int,int> is foo<ReturnT=int, ParamsT starts with {int}>.

    It does not fully specify ParamT. In fact, there is no way to fully specify ParamT.

    As an incompletely specified template, deduction occurs, and fails. It doesn't try "what if I just assume the pack doesn't go any further".

    You can fix this with:

    template<typename ReturnT, typename... ParamT>
    void foo(block_deduction<std::function<ReturnT(ParamT...)>> callback)
    {}
    

    where block_deduction looks like:

    template<class T>
    struct block_deduction_helper { using type=T; }:
    template<class T>
    using block_deduction = typename block_deduction_helper<T>::type;
    

    now deduction is blocked on foo's first argument.

    And your code works.

    Of course, if you pass in a std::function it will no longer auto-deduce arguments.

    Note that deducing the type of a a type erasure type like std::function is usually code smell.

    Replace both with:

    template<class F>
    void bar(F callback)
    {}
    

    if you must get arguments, use function traits helpers (there are many on SO). If you just need return value, there are std traits that already work that out.


    In c++17 you can do this:

    tempate<class R, class...Args>
    void bar( std::function<R(Args...)> f ) {}
    template<class F>
    void bar( F f ) {
      std::function std_f = std::move(f);
      bar(std_f);
    }
    

    using the c++17 deduction guides feature.

    0 讨论(0)
  • 2021-02-07 22:32

    You don't have any deduction for the type parameters of bar, they are fully specified.

    You still have the tail of the pack to deduce in foo, and that fails because the lambda isn't a std::function.

    0 讨论(0)
提交回复
热议问题