gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:00:52 24 4
gpt4 key购买 nike

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

error: no matching function for call to Foo<int>(bool (&)(int))


为什么编译器会引发错误? Foo有什么区别吗的和 Bar的模板参数类型在 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;
}
See Compiler Explorer for a live example .
我也尝试更改 Foo有点功能,它以某种方式工作:
template<typename... Args>
void Foo(bool(*predicate)(Args...)) {
std::function<bool(Args...)> func(predicate);
}
我要 std::function Foo 中的类型参数功能,但我不知道怎么做

最佳答案

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

int main() {
Foo<int>( std::function<bool(int){predicate} );
//OR
Foo<int>( {predicate} );
return 0;
}

关于c++ - 使用 std::function 和模板参数将函数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63631769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com