【发布时间】:2020-12-17 06:27:10
【问题描述】:
我正在尝试将指向谓词函数的指针传递给Foo 和Bar 函数。
Bar 函数可以正常工作,但 Foo 函数会引发编译时错误:
错误:没有匹配函数调用
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);
}
我想在Foo 函数中有std::function 类型参数,但我不知道该怎么做
【问题讨论】:
标签: c++ templates variadic-templates type-inference std-function