Invalid use of a non-static member function

I have something like this:

class Bar { public: pair<string,string> one; std::vector<string> cars; Bar(string one, string two, string car); }; class Car { public: string rz; Bar* owner; Car(string car, Bar* p); }; class Foo { public: Foo ( void ); ~Foo ( void ); int Count ( const string & one, const string & two) const; int comparator (const Bar & first, const Bar & second) const; std::vector<Bar> bars; }; int Foo::comparator(const Bar & first, const Bar & second) const{ return first.name < second.name; } int Foo::Count ( const string & one, const string & two ) const{ int result=0; Bar mybar = Bar( one, two, "" ); std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator); if (ToFind != bars.end() && ToFind->one == mybar.one ){ result = ... } return result; } 

The Foo::Count method should use std::lower_bound() to find the element in vector<Bar> according to a pair of two lines. Now the part that doesn't work. For lower_bound() I provide a comparator() method. I thought everything was fine, but g ++ says:

 c.cpp: In member function 'int Foo::Count(const string&, const string&) const': c.cpp:42:94: error: invalid use of non-static member function std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator); 

And the Count() method should remain const ...

I am new to C ++ because I have to learn it.

Any ideas?

+6
source share
3 answers

You have to make Foo::comparator static or wrap it in an object of class std::mem_fun . This is because lower_bounds expects the comparator to be a class of an object that has a call statement, such as a function pointer or functor object. In addition, if you are using C ++ 11 or later, you can also use dwcanillas and use the lambda function. C ++ 11 also has std::bind .

Examples:

 // Binding: std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2)); // Lambda: std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; }); 
+3
source

The simplest solution is to make the comparator function static:

 static int comparator (const Bar & first, const Bar & second); ^^^^^^ 

When called in Count its name will be Foo::comparator .

Now that you have this, it does not make sense to be a non-static member function because it does not use any member variables of Foo .

Another option is to make it a non-member function, especially if it makes sense that this comparator can be used by code other than Foo .

+6
source

You must pass the this pointer to tell the function for which the object works, because it relies on this, unlike the static member function.

0
source

Source: https://habr.com/ru/post/984284/


All Articles