简体   繁体   English

std :: function的类型推导

[英]Type deduction for std::function

The following code is not going to compile because of not calling a matching std::function constructor at the compile time. 以下代码不会编译,因为在编译时没有调用匹配的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;
}

But is it possible to provide the same (or similar) functionality as expected in the example above? 但是,是否可以提供与上述示例中预期相同(或类似)的功能? Is there an elegant way to have a function accepting any 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;
}

Live sample at http://melpon.org/wandbox/permlink/zpkZI3sn1a76SKM8 现场样本http://melpon.org/wandbox/permlink/zpkZI3sn1a76SKM8

Take the callable type as a template parameter: 将可调用类型作为模板参数:

template <typename Func, typename Arg>
auto invoke(Func&& f, Arg&& x) -> decltype(f(std::forward<Arg>(x))) {
    return f(std::forward<Arg>(x));
}

I would go one step further and take a parameter pack for the arguments so that you aren't limited to single-arg callables: 我会更进一步,为参数采用参数包,这样你不仅限于单arg callables:

template <typename Func, typename... Args>
auto invoke(Func&& f, Args&&... x) -> decltype(f(std::forward<Args>(x)...)) {
    return f(std::forward<Args>(x)...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM