Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: using class member and static function of same name but different parameters fails

I want to have a class with a static and a member function of the same name and doing exactly the same thing. Once to be able to call it from an instance, and once to use it with functions from std-algorithm. Minimal example:

#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;
}

The above code compiles and works as expected. However, if I uncomment the member function isOne(), because, maybe, I would also like to have

foo x; x.isOne();

in my main(), things break horribly both with clang 6.0 and gcc 5.3. The clang error is

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)

and the gcc error is basically the same in a different wording.

I am obviously doing things wrong, but I am currently out of ideas how to fix this. Any pointers appreciated.

like image 966
BaCh Avatar asked Oct 18 '25 16:10

BaCh


1 Answers

when taking a pointer to an overloaded method you need to tell the compiler which overload you want to take a pointer to, you can do this with a static cast to the appropriate method type:

 auto numones=std::count_if(v.begin(), v.end(), static_cast<bool(*)(const foo&)>(foo::isOne));
like image 64
Alan Birtles Avatar answered Oct 22 '25 05:10

Alan Birtles