Why an element of a vector<std::function> can bind to different function signatures in C++?

Viewed 76

I created an vectorstd::function with a specified function type, as follows.

std::vector<std::function<void(int)>> v;

The type of the elements in this vector should be void(int), but I can push other function types into it, like:

    v.emplace_back([](int x) -> int {
        return 1;
    });

The complete codes are:

int main()
{
    std::vector<std::function<void(int)>> v;
    v.emplace_back([](int x) -> int {
        return 1;
    });
}

And it is compiled successfully, why compiler did not complain about this type error?

Even if the compiler reports an error only when this element is called explicitly in the code, why is it not reported when it is not called explicitly?

1 Answers

In std::function<R(Ts...)>, you can store any callable g as long as as it can be called with Ts objects and returns R-like object.

Meaning g does not have to have the same arguments, only those implicitly-convertible from Ts. Regarding the return value

  • if R is void, g can return anything and it will be ignored.
  • if not, g must return something implicitly convertible to R.
Related