Std::is_function不能将模板参数识别为函数

std::is_function does not recognize template argument as function

本文关键字:参数 识别 函数 is function 不能 Std      更新时间:2023-10-16

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

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)。为什么会这样呢?在这种情况下,我如何识别函数或指向函数的指针?

F是指向函数的指针(无论您传递的是f还是&f)。所以移除指针:

std::is_function<typename std::remove_pointer<F>::type>::value

(std::is_function<std::function<FT>> == false;-))