是,您可以:
虽然类型系统是一个有点令人费解。
所以通常在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.
[C++不具有程序,它具有的功能](https://www.google.com/#q=call%20function%20via %20pointer%20c%2B%2B) – 2012-08-09 14:35:14
指向函数的指针称为[函数指针](http://en.wikipedia.org/wiki/Function_pointer),是的,可以通过函数指针调用函数。 – 2012-08-09 14:35:18
为了这个问题,将“FunctionWithVeryVeryVeryLongNameThatPrintsTheCurrentClockStateUsingStdCoutOutputStream”的名称缩短为“print_clock_state”太难了吗? – mfontanini 2012-08-09 14:36:20