std :: is_function不识别模板参数作为函数

std :: is_function不识别模板参数作为函数

问题描述:

我将函数的指针传递给函数模板:

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 ;-))