Compiler does not deduce template parameters (map std::vector -> std::vector)

后端 未结 1 457
一整个雨季
一整个雨季 2020-12-06 11:29

I have the following template.

template
std::vector map(const std::vector &v, std::function

        
1条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 12:12

    Your function expects an std::function argument, but you're calling it with a lambda expression instead. The two are not the same type. A lambda is convertible to std::function, but template argument deduction requires exact matches and user defined conversions are not considered. Hence the deduction failure.

    Deduction does work if you actually pass an std::function to map().

    std::function fn = [] (int x) { return string(x,'X'); };
    vector strings = map(numbers, fn);
    

    Live demo


    One possible workaround to avoid having to specify the template arguments is to modify the function to accept any kind of callable, rather than an std::function object.

    template
    std::vector::type>
        map(const std::vector &v, Func f) {
            // ...
        }
    

    Another version of the same idea, using decltype and declval instead of result_of

    template
    std::vector()(std::declval()))>
        map(const std::vector &v, Func f) {
            // ...
        }
    

    Finally, using a trailing return type

    template
    auto map(const std::vector &v, Func f) 
      -> std::vector {
            // ...
        }
    

    Live demo

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