小编Oli*_*uez的帖子

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,是否可以提供与上述示例中预期相同(或类似)的功能?是否有一种优雅的方式来接受任何可调用的函数:

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
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 std-function

4
推荐指数
2
解决办法
246
查看次数

标签 统计

c++ ×1

c++11 ×1

std-function ×1

templates ×1