Question

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 !

Was it helpful?

Solution 2

The parenthesis are wrong:

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

OTHER TIPS

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))()).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top