Why does this construction of std::function from lambda not compile?

Why doesnt the following line compile?

std::function<void (int)> f = [](int&){};

But many other alternatives do:

    [[maybe_unused]]
    std::function<void (const int&)> f1 = [](const int&){};
    //[[maybe_unused]]
    // doesnt compile because losing constness
    //std::function<void (const int&)> f2 = [](int&){}; 
    [[maybe_unused]]
    std::function<void (const int&)> f3 = [](int){};
    [[maybe_unused]]
    std::function<void (const int&)> f4 = [](const int){};
    [[maybe_unused]]
    std::function<void (int&)> f5 = [](const int&){};
    [[maybe_unused]]
    std::function<void (int&)> f6 = [](int&){};
    [[maybe_unused]]
    std::function<void (int&)> f7 = [](int){};
    [[maybe_unused]]
    std::function<void (int&)> f8 = [](int){};
    [[maybe_unused]]
    std::function<void (const int)> f9 = [](const int&){};
    //[[maybe_unused]]
    // doesnt compile because losing constness
    //std::function<void (const int)> f10 = [](int&){};
    [[maybe_unused]]
    std::function<void (const int)> f11 = [](const int){};
    [[maybe_unused]]
    std::function<void (const int)> f12 = [](int){};
    [[maybe_unused]]
    std::function<void (int)> f13 = [](const int&){};
    //[[maybe_unused]]
    // doesnt compile because ??
    //std::function<void (int)> f14 = [](int&){};
    [[maybe_unused]]
    std::function<void (int)> f15 = [](const int){};
    [[maybe_unused]]
    std::function<void (int)> f16 = [](int){};

My understanding was that std::function have a () operator which takes the args and calls the functor's () operator with the args so its possible that for e,g, - first one takes const ref and next takes copy.

With this line of logic, I would think that a int copy should be able to be passed forward as int&. Can someone explain?


Solution 1:

std::function forwards it's arguments to it's target. The lambda assigned to f14 can't be called with an rvalue.

You are also incorrect about f10, that is the same case as f14. Top level const is ignored in arguments. Each of f11, f12, f15 and f16 are the same case.