STD ::功能的类型扣除额

Type deduction for std::function

本文关键字:扣除额 类型 功能 STD      更新时间:2023-10-16

以下代码不会在编译时间调用匹配的std ::函数构造函数。

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;
}

但是是否可以提供与上面示例相同(或相似)的功能?是否有一种优雅的方法可以接受任何可召唤的功能:

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

实时样本

以模板参数为单位:

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

我会再进一步进行参数,以便您不仅限于单arg可可:

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