我希望使用std::function类型,以便在赋值时检查函数签名。但我无法理解在这种情况下发生了什么。
//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
f的行为是我想要的,但是我认为"fct=g;"会导致编译时错误。
请问这种情况有什么解释吗?
int
,所以返回类型不应该有影响。当代码调用fct(2.5)
时,由于fct ::operator()
仅接受int
,因此它将2.5转换为2。 - Gaurav Dhiman