mercredi 16 octobre 2019

Get reference to member function overloaded by const specification

Here is some class with two overloaded methods foo:

class Object {
public:
    Object (double someVal) : val(someVal) { }
    double getter () const { return val; }
    double& getter () { return val; }
private:
    double val;
};

So now the double Object::getter() const function will be called on const instances

const Object instance(42);
cout << instance.getter() << endl; // called: `double getter() const`

Now, I am trying to get reference to double getter() const function and assign it to std::function type

const Object instance(42);
function<double(const Object&)> foo = &Object::getter;
cout << foo(instance) << endl;

The code works fine if function double& getter() is removed, but with it I got the following error on the second line:

test.cpp:18:34: error: no viable conversion from '<overloaded function type>' to
      'function<double (const Object &)>'
        function<double(const Object&)> foo = &Object::getter;
                                        ^     ~~~~~~~~~~~~~~~

It seems that error happens, because system tries to call double& getter(). The question is how to force calling of double getter() const? The full listing is attached here

Aucun commentaire:

Enregistrer un commentaire