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

Hak*_*ell 6 c++ templates type-inference variadic-templates std-function

我试图将一个指向谓词函数的指针传递给FooBar函数。该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[]) {
    // gcc: error: no matching function for call to
    //      'Foo<int>(bool (&)(int))'
    Foo<int>(predicate);
    Bar<int>(predicate);
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请参阅编译器资源管理器以获取实时示例

我还尝试Foo稍微更改该功能,但它以某种方式起作用:

template<typename... Args>
void Foo(bool(*predicate)(Args...)) {
  std::function<bool(Args...)> func(predicate);
}
Run Code Online (Sandbox Code Playgroud)

我想std::functionFoo函数中有类型参数,但我不知道该怎么做

Waq*_*med 1

该错误是因为 的确切类型std::function与 不同predicate。为了解决这个问题,您可以显式调用 的构造函数std::function

int main() {
    Foo<int>( std::function<bool(int){predicate} );
    //OR
    Foo<int>( {predicate} );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)