2011-12-27 60 views
0

閱讀「C++模板:完整指南」第22.5.3節函數調用語法?

我很困惑作者用於函數指針的語法。我相信這個語法被稱爲「函數調用語法」?我覺得我在這裏失去了一些東西..?我評論了有關代碼的部分。

template<typename F> 
void my_sort(.., F cmp = F()) 
{ 
    .. 
    if (cmp(x,y)) {..} 
    .. 
} 

//*** WHAT IS THIS SYNTAX? *** 
bool my_criterion()(T const& x, T const& y); 

// call function with function pointer passed as value argument 
my_sort(..., my_criterion); 

我取代所有..的適當的值,並在my_criterion()代替第t爲int,它仍然不能編譯。

他首先提到此語法是之前的章節:

「作爲寫入,這算符規範技術的優點是,它也可以通過一個普通的函數指針作爲參數,例如:

bool my_criterion() (T const& x, T const& y); 

我試圖根據從書中摘錄編譯代碼:

template<typename F> 
void mySort(F cmp) 
{ 
    std::cout << "mySort(F cmp)" << std::endl; 
} 

bool myCriterion()(int x, int y); 

*錯誤C2091:函數返回功能(指myCriterion)

+1

什麼是錯誤信息?另外,請發佈一些*實際*代碼。 – 2011-12-27 19:41:25

+0

錯誤:C2091:函數返回函數。我逐字複製了書中的代碼。 – Integer 2011-12-27 19:51:45

+0

我的意思是你實際試圖編譯的代碼。 – 2011-12-27 19:53:03

回答

1

我會猜測這是書中的一個錯字。從書中引用:

As written, the advantage of this functor specification technique is that it is also possible to pass an ordinary function pointer as argument. For example:

bool my_criterion() (T const& x, T const& y); 
// call function with function object 
my_sort (… , my_criterion); 

作者顯然試圖聲明和「普通功能」。函數名稱後面的一對括號不應該在那裏。

0

我想你缺少的是一種叫做仿函數類:

這裏是一個小例子。

#include <iostream> 
#include <string> 
#include <sstream> 


struct foobar { 
    void operator()(int x, int y) { 
    std::cout << x << y << std::endl; 
    } 
}; 

int main() { 
    foobar()(10,20); 
    return 0; 
}