小编Hak*_*ell的帖子

使用 std::function 和模板参数将函数传递给函数

我试图将一个指向谓词函数的指针传递给Foo和Bar函数。该Bar函数工作正常,但该Foo函数引发编译时错误:

错误:没有匹配的调用函数 Foo<int>(bool (&)(int))

为什么编译器会引发错误?' 解包后' Foos 和Bar's 模板参数类型之间有什么区别Args吗?

#include <functional>

bool predicate(int a) {
    return (a > 5);
}

// sizeof...(Args) == 1 and I suppose it is int
template<typename... Args>
void Foo(std::function<bool(Args...)> predicate) {
    // clang: note: candidate template ignored:
    //        could not match 'function<bool (int, type-parameter-0-0...)>' 
    //        against 'bool (*)(int)'
}

template<typename Args>
void Bar(std::function<bool(Args)> predicate) {

}

int main(int argc, char const *argv[]) …
Run Code Online (Sandbox Code Playgroud)

c++ templates type-inference variadic-templates std-function

6
推荐指数
1
解决办法
153
查看次数