lambda参数推断不正确

fet*_*tag 1 c++ lambda c++14 c++17

为什么这个代码在C++ 14甚至C++ 17下是不正确的?

template <typename T>
function<T(T, T)> ReturnLambda () {
    return [] (T x, T y) { return x*y; };
    // return [] (auto x, auto y) { return x*y; };    // also incorrect
}


int main() {
    auto f = ReturnLambda();
    cout << f(3, 4) << endl;

}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

模板参数推导仅适用于函数参数,ReturnLambda()而不具有任何功能参数; T在调用时ReturnLambda(),没有办法推断出模板参数; 你必须明确指定它.例如

auto f = ReturnLambda<int>();
Run Code Online (Sandbox Code Playgroud)