简体   繁体   中英

Unary predicate with member function

I would like to use a unary function to look up a certain parameter name in a list with std::find

class Parameter {
    public:
        string getName() { return mName;}
        //string mName;
    private:
        string mName;
        string mType;
        string mValue;
    };

    class Param_eq : public unary_function<Parameter, bool> {
        string mName;
    public: 
        Param_eq (const string& name) : mName(name) {}
        bool operator() (const Parameter& par) const { 
            return (mName == par.getName());
        }
    };

    double Config::getDouble(string& name) {
        list<Parameter>::iterator iParam = find(mParamList.begin(), mParamList.end(), Param_eq(name));
        double para = iParam->getDouble();
        return para;
    }
}

But I get the following compiler error

error C2662: 'Parameter::getName' : cannot convert 'this' pointer from 'const Parameter' to 'Parameter &'
Conversion loses qualifiers

If I make the member variable Parameter::mName public and use it instead of the member function Parameter::getName() in the return statement of Param_eq::operator() it compiles without error.

bool operator() (const Parameter& par) const { 
    return (mName == par.mName);
}

Why is that? Both member variable and member function are string type.

How do I get the above example to work by using a member function?

The error tells you that you are calling a non-const method on a const reference. A non-const method may modify member variables and thus violate the const constraint.

You can solve this two ways:

  1. Don't call the method at all and access the mName variable directly:

     bool operator() (const Parameter& par) const { return (mName == par.mName); } 

    Note that this does not require making mName public. This works because operator() is a member of the Parameter class. Remember that private members are accessible in any method of the class. It does not matter whether you access the private members of another instance of the same class or not.

  2. Declare getName() to be const objects:

     string getName() const { return mName;} 

    Note the location of the const qualifier. This tells the compiler that the method will not modify any member variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM