以下代码不会编译,因为在编译时未调用匹配的 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
?
#include <functional>
#include <cassert>
template <typename F, typename X>
auto invoke(F&& f, X x) -> decltype(std::forward<F>(f)(x)) {
return std::forward<F>(f)(x);
}
int func(char x) {
return 2 * (x - '0');
}
bool someFunction(double) {return false;}
int main() {
auto val = invoke(func, '2');
assert(val == 4);
auto val2 = invoke([](int x) -> int { return x/2; }, 100);
assert(val2 == 50);
bool (*func_ptr)(double) = &someFunction;
bool b = invoke(func_ptr, 3.141);
return 0;
}
现场样品位于http://melpon.org/wandbox/permlink/zpkZI3sn1a76SKM8 http://melpon.org/wandbox/permlink/zpkZI3sn1a76SKM8
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)