以下代码不会编译,因为在编译时没有调用匹配的std :: function构造函数.
template <typename X, typename Y>
Y invoke(std::function<Y(X)> f, X x) {
return f(x);
}
int func(char x) {
return 2 * (x - '0');
}
int main() {
auto val = invoke(func, '2');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,是否可以提供与上述示例中预期相同(或类似)的功能?是否有一种优雅的方式来接受任何可调用的函数:
invoke([](int x) -> int { return x/2; }, 100); //Should return int == 50
bool (*func_ptr)(double) = &someFunction;
invoke(func_ptr, 3.141); //Should return bool
Run Code Online (Sandbox Code Playgroud)
?