Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::function type cheking correct?

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 ?

like image 956
chetzacoalt Avatar asked Nov 26 '25 21:11

chetzacoalt


1 Answers

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
like image 168
bolov Avatar answered Nov 28 '25 15:11

bolov