2013-01-10 28 views
0

我有一個仿函數類從unary_function繼承的函數:謂詞算符從unary_function繼承,也就是沒有服用1個參數

template<class T> 
class Matcher : public std::unary_function<T, bool> 
{ 
private: 
    int m_match; 

public: 
    Matcher(int valToMatch) : m_match(valToMatch) { }; 
    bool operator() (T toTest) 
    { 
     return T.prop == m_match; 
    } 
} 

其使用的這些事情之一的函數:

void DoStuff(std::unary_function<ThisType, bool> & pred, 
      vector<ThisType> & stuffToTest) 
{ 
    for(vector<ThisType>::iterator it = stuffToTest.begin(); 
     it != stuffToTest.end(); ++it) 
    { 
     if(pred(*it))  // <<< Compiler complains here 
     { 
      // do stuff 
     } 
    } 
} 

原來的調用函數:

Matcher myMatcher<ThisType>(n); 
// have vector<ThisType> myStuff 
DoStuff(myMatcher, myStuff); 

據我知道,我有一個模板函子的whic h我正在構造一個帶有ThisType類型的實例,我將這個類型傳遞給期待unary_function參數的函數,並調用一個ThisType實例。

但編譯器抱怨說「術語不計算一個帶有1個參數的函數」。

我錯過了什麼?

回答

5

這是因爲即使您將派生類對象傳遞給函數,函數參數仍然是std::unary_function,它沒有成員operator()接受一個參數。因此錯誤。

我建議你給你的函數更改爲函數模板爲:

template<typename F> 
void DoStuff(F && pred, vector<ThisType> & stuffToTest) 
{ 
    for(auto it = stuffToTest.begin(); it != stuffToTest.end(); ++it) 
    { 
     if(pred(*it)) 
     { 
      // do stuff 
     } 
    } 
} 
+0

很清楚。這裏只有模板化DoStuff的問題是它已經是特定於ThisType的,所以謂詞將始終爲pred(ThisType)。 –

+0

@PhilH:那應該沒關係。如果你願意,你可以使用'std :: function '作爲參數類型,但我不會建議這樣做,因爲它阻礙了優化,並且由於類型擦除會產生較慢的代碼,其他的手模板代碼會產生更快的代碼,因爲它可能內聯仿函數。 – Nawaz

+0

然後,我必須重新思考,因爲這是在C++的pre-0x(但是帶有tr1)版本中。 –

2

unary_function是不是多態類型,它只是一個基類,它有提供argument_typeresult_type成員類型。

你可以傳給你的DoStuff功能std::function<bool(ThisType)>,或者你讓你DoStuff函數模板

+0

乾杯,不幸的是我只用這個編譯器無法訪問C++ 11。 –