gpt4 book ai didi

c++ - std::function 的类型推导

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:30 27 4
gpt4 key购买 nike

以下代码不会编译,因为在编译时没有调用匹配的 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

关于c++ - std::function 的类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com