问题描述
我将函数的指针传递给函数模板:
I am passing a pointer to function into a function template:
int f(int a) { return a+1; }
template<typename F>
void use(F f) {
static_assert(std::is_function<F>::value, "Function required");
}
int main() {
use(&f); // Plain f does not work either.
}
但模板参数 F
不能被 is_function
识别为一个函数,静态断言失败。编译器错误消息说, F
是 int(*)(int)
这是一个指向函数的指针。为什么它会这样?在这种情况下,如何识别函数或函数的指针?
But the template argument F
is not recognized by is_function
to be a function and the static assertion fails. Compiler error message says that F
is int(*)(int)
which is a pointer to function. Why does it behave like that? How can I recognize the function or pointer to function in this case?
推荐答案
F
是指向函数的指针(无论是否通过 f
或& f
)。因此请移除指针:
F
is a pointer to function (regardless of whether you pass f
or &f
). So remove the pointer:
std::is_function<typename std::remove_pointer<F>::type>::value
(讽刺的是, std :: is_function< std :: function< FT> ; == false
; - ))
(Ironically, std::is_function<std::function<FT>> == false
;-))
这篇关于std :: is_function不识别模板参数作为函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!