我有一個仿函數類從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個參數的函數」。
我錯過了什麼?
很清楚。這裏只有模板化DoStuff的問題是它已經是特定於ThisType的,所以謂詞將始終爲pred(ThisType)。 –
@PhilH:那應該沒關係。如果你願意,你可以使用'std :: function'作爲參數類型,但我不會建議這樣做,因爲它阻礙了優化,並且由於類型擦除會產生較慢的代碼,其他的手模板代碼會產生更快的代碼,因爲它可能內聯仿函數。 –
Nawaz
然後,我必須重新思考,因爲這是在C++的pre-0x(但是帶有tr1)版本中。 –