我正在将一个指向函数的指针传递到一个函数模板中:
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)
。为什么会出现这种情况?在这种情况下,我如何识别函数或指向函数的指针?
std::is_function
是主要的分类特征之一。is_callable
或类似的东西将完全服务于不同的目的。 - Luc Dantonstd::is_function
的价值,它非常适用于像std::is_array
(该函数也不应该对std::array
返回 true) 或std::is_class
等情景中。但是,在其他相当高级别的特性(如已经提议的std::is_swappable
以及迫切需要的(尽管我不确定是否已经提出)std::is_hashable
)中增加一个额外的std::is_callable
将是个好主意,并且与其他高级别特性保持一致。 - Christian Rau