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
is flexible and uses type erasure
underneath, so if you have std::function
object with with signature std::function<R(Args...)>
, it will accept any Callable
that can be called with type Args...
and returns type R
,
So in your case for std::function<int(int)>
, function of type int g(double);
can be called with type int
arguments compiler will just promote int
to double
,
If you run this code
#include <iostream>
#include <functional>
int f(int x) { std::cout << x << " " << "//f:int->int\n"; return x; }
int g(double x) { std::cout << x << " " << "//g:double->int\n"; return 1; }
int main()
{
std::function<int(int)> fct;
fct = f; fct(1);
fct = g; fct(2.5);
}
You can see that fct
will only accept int
and afterwards compiler promote it to double
, So In the output of fct(2.5);
it will print 2 //g:double->int
and not 2.5 //g:double->int