I've got the following code, which can't be compiled
template <typename T>
void call_with(std::function<void(T)> f, T val) {
f(val);
}
int main() {
auto print = [](int x) { std::cout << x; };
call_with(print, 42);
}
And the compilation error looks like
tst.cpp:17:2: error: no matching function for call to 'call_with'
call_with(print, 42);
^~~~~~~~~
tst.cpp:11:6: note: candidate template ignored: could not match 'function<void (type-parameter-0-0)>' against
'(lambda at tst.cpp:16:15)'
void call_with(std::function<void(T)> f, T val) {
^
1 error generated
I tried to compile it with g++ tst.cpp -o tst -std=c++17
So I know sometimes C++ can deduce template arguments under some conditions, but I'm wondering why it cannot compile this code in this case. It looks like there cannot be any other options for a type T
to be anything, but int and for f
to be anything but std::function<void(int)>
.