是,您可以:
雖然類型系統是一個有點令人費解。
所以通常在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