簡體   English   中英

std :: function的類型推導

[英]Type deduction for std::function

以下代碼不會編譯,因為在編譯時沒有調用匹配的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;
}

但是,是否可以提供與上述示例中預期相同(或類似)的功能? 是否有一種優雅的方式來接受任何可調用的函數:

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