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

标签 c++ c++11 templates 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;
}

但是是否有可能提供与上面示例中预期的相同(或相似)的功能?有没有一种优雅的方法可以让函数接受任何 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/

相关文章:

C++ 部分类模板针对多个参数的特化

c++ - 无法调用继承的 protected 泛型类成员

c++ - 以下包扩展有什么问题?

c++ - G++ -M32 -M64 在 Windows 上切换

c++ - 用于添加和比较 Integer 和 Fraction 类数据的运算符重载

c++ - 虚拟析构函数改变 decltype 的行为

c++ - 为什么来自 Bjarne 的 "Tour of C++"的代码有效?

c++ - 字符数组的Initializer-String太长

c++ - 如何编写可以迭代泛型类型的函数

c++ - 带有模板函数和 'using namespace' 的 VS2008(+?) 编译器错误