2

Here is a functor used to filter a list of objects. It must be instanciated with a pointer to member function of the objects' class, as a way to access different elements.

class Filter_Compare : public Filter { std::string (File::*fun)(); public: Filter_Compare(const char *name, const char *desc, std::string (File::*f)()) : Filter(name, desc), fun(f) {} ~Filter_Compare() {}; int operator () (File* f1, File* f2) { return this->eval(*f1, *f2); } int eval(File* f1, File* f2) const { return this->eval(*f1,*f2); } int eval(File& f1, File& f2) const { return f1.*(this->fun()).compare(f2.*(this->fun())); } }; //an instanciation example : Filter_Compare fname("Name", "Compare by name", File::getPath); 

And g++ returns these error :

Filter.h: In member function ‘int Filter_Compare::eval(File&, File&) const’: Filter.h:48:27: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((const Filter_Compare*)this)->Filter_Compare::fun (...)’, e.g. ‘(... ->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)’ Filter.h:48:53: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((const Filter_Compare*)this)->Filter_Compare::fun (...)’, e.g. ‘(... ->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)’

I don't see the problem here, as I've already used this on another class without any error (well, at least it compile, I couldn't run it right now), where the code is :

lit_type eval(File& f) const { return f.*(this->fun()) - thValue; }

What exactly is wrong here ? I don't know how I could make a reference to the pointer another way. Thanks !

0

2 Answers 2

1

To call through a pointer-to-member-function you use .* or ->*. To call fun on the File& f1, the call is (f1.*fun)(). So: (f1.*fun)().compare((f2.*fun)()). If you want to complexify the expression with explicit this->s that aren't needed, you have to be extra careful: (f1.*(this->fun))().compare((f2.*(this->fun))()).

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think you got the parenthesis right either. I believe it should be (f1.*fun)() (i.e. the () take precedence over .*)
@DavidRodríguez-dribeas - you're probably right. That's what I get for not compiling the code. Fixed.
0

The parenthesis are wrong:

int eval(File& f1, File& f2) const { return (f1.*fun)().compare((f2.*fun)()); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.