是的你可以:
虽然类型系统有点复杂。
因此,通常将指向函数的指针包装在 typedef 中。
typedef <returnType> (*<TypeName>)(<ParameterList>);
// In your case:
tpyedef void (*PtrToTimeFunc)();
// Now your pointer types look like normal variables:
PtrToTimeFunc pf = &PrintCurrentTimeStamp;
// Calling them is like normal:
pf(); // If it needed parameters then put them as normal.
因为C++编译器不能通过函数指针来优化代码;在 C++ 中,通常使用函子。仿函数是一个行为类似于函数的对象,但是因为它是一个对象,所以也可以包含状态(就像其他语言中的闭包一样)。
struct MyFunctor
{
// To make a functor just override the operator ()
// You can make it return any type and take any parameters (just like a function).
int operator()() const
{
return time(NULL);
}
// Add any state and constructors etc. you like here.
// Though note: because I declared the operator() as const you
// can not mutate the state via the function call (remove cost)
// if you want to do that.
};
// declaring a functor just like any-other object.
MyFunctor myFunctor;
// calling. Just like a function.
myFunctor();
好的。那么为什么这比指针更有用。
与标准算法一起使用时。您使用类型定义算法,functor
因此编译器生成算法代码,它还具有函子的所有代码(与过去无法优化的函数指针不同)。这允许编译器就地进行一整套优化。
std::generate(cont.begin(), cont.end(), myFunctor);
所以在 C++ 11 中我们引入了 lambdas。这些基本上是可以就地定义的功能。但更容易将 lambdas 视为编译器生成的函子(因为它们can
将当前状态作为定义的一部分)。
std::generate(cont.begin(), cont.end(), [](){return time(NULL);});
// [] - defines the state that is being captured.
// Think of this like the constructor capturing objects.
// In this case take no state.
//
// () - parameter list
// In this case no parameters
//
// {} - The code.
一个更有趣的例子:
std::vector<int> data; // fill vector
std::for_each(data.begin(), data.end(), [](int& value){value += 4;}); // Add 4 to each member.