关键是函数指针在泛型编程中一直“在后台”使用。人们往往会忘记这一点,因为模板参数推导隐藏了函数指针语法。
例如:
#include <algorithm>
#include <iterator>
bool f(int i)
{
return i == 1;
}
int main()
{
int arr[] = { 1, 1, 3 };
int count = std::count_if(std::begin(arr), std::end(arr), f);
}
main 的最后一行中的f是一个函数指针,因为std::count_if 模板函数将接受任何可以与() 语法一起使用的东西。引用cppreference.com:
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );
UnaryPredicate可以是一个函数指针,在上面的例子中就是一个。
编译器只是在您传递f 时自动推断出它的确切类型bool(*)(int)。从技术上讲,您也可以这样编写调用:
// just for illustration:
std::count_if<int*, bool(*)(int)>(std::begin(arr), std::end(arr), f);
如果 C++ 中没有函数指针,那么您不能直接将函数用作标准库算法中的谓词。相反,您必须始终将它们包装在类中:
#include <algorithm>
#include <iterator>
bool f(int i)
{
return i == 1;
}
struct Functor
{
bool operator()(int i) const
{
return f(i);
}
};
int main()
{
int arr[] = { 1, 1, 3 };
int count = std::count_if(std::begin(arr), std::end(arr), Functor());
}