Phi*_*l H 0 c++ stl predicate functor
我有一个继承自unary_function的仿函数类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下某项功能的功能:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
原始呼叫功能:
Matcher myMatcher<ThisType>(n);
// have vector<ThisType> myStuff
DoStuff(myMatcher, myStuff);
Run Code Online (Sandbox Code Playgroud)
据我所知,我有一个模板化仿函数,我正在构建一个具有ThisType类型的实例,我将其传递给期望unary_function参数的函数,并使用ThisType实例调用.
但是编译器抱怨说"术语不会评估为带有1个参数的函数".
我错过了什么?
这是因为即使你将派生类对象传递给函数,函数参数仍然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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |