I wish to use std::function type from so that function signature is checked on assignment. But I fail to understand what is happening in this case
//g++ 5.4.0
#include <iostream>
#include <functional>
int f(int x) { std::cout << "//f:int->int\n"; return x; }
int g(double x) { std::cout << "//g:double->int\n"; return 1; }
int main()
{
std::function<int(int)> fct;
fct = f; fct(1);
fct = g; fct(1);
}
//trace
//
//f:int->int
//g:double->int
The behavior for f is what I want, but I thought that "fct=g;" would cause a compile time error.
Any light on this case please ?
std::function accepts any callable that where the parameters can be converted and the return type is convertible. If they aren't you get a compilation error. For instance:
int h(double& x);
std::function<int(int)> fct;
fct = h; // <- compiler error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With