【发布时间】:2018-03-10 21:08:56
【问题描述】:
我希望有一个具有静态和同名成员函数的类,并且做完全相同的事情。一次可以从实例中调用它,一次可以将它与标准算法中的函数一起使用。最小的例子:
#include <algorithm>
#include <vector>
class foo {
public:
inline static bool isOne(const foo & s) {
return s.bar == 1;
}
// if I uncomment the next line, count_if won't compile anymore
//inline bool isOne() const { return isOne(*this); }
private:
int bar;
};
int main()
{
std::vector<foo> v;
auto numones=std::count_if(v.begin(), v.end(), foo::isOne);
return 0;
}
上面的代码按预期编译和工作。但是,如果我取消注释成员函数 isOne(),因为,也许,我也想拥有
foo x; x.isOne();
在我的 main() 中,clang 6.0 和 gcc 5.3 的情况都非常糟糕。铿锵的错误是
no matching function for call to 'count_if'
note: candidate template ignored: couldn't infer template argument '_Predicate'
count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
和gcc的错误基本上是一样的,换个说法。
我显然做错了,但我目前不知道如何解决这个问题。任何指针表示赞赏。
【问题讨论】:
标签: function c++11 static stl member