【发布时间】:2017-03-13 20:52:44
【问题描述】:
以下代码不会编译,因为在编译时没有调用匹配的 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;
}
但是是否可以提供与上述示例中预期的相同(或相似)的功能?有没有一种优雅的方法可以让函数接受任何 Callable:
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
?
【问题讨论】:
-
看看 C++17 中的
std::invoke。
标签: c++ c++11 templates std-function