lundi 29 juin 2015

Function overloading with std::function argument: why is the const method never called?

#include <functional>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A
{
    public:
    void doStuff(function<void (const string *)> func) const
    {
        cout << "Const method called" << endl;
        for(const auto& i_string : m_vec)
            func(i_string);
    }

    void doStuff(function<void (string *)> func)
    {
        cout << "Non-const method called" << endl;
        doStuff([&func](const string *str)
        {
            auto mutableString = const_cast<string *>(str);
            func(mutableString);
        });
    }

private:
    vector<string *> m_vec;
};

int main()
{
    auto a = A{};

    a.doStuff([](string *str){
        *str = "I modified this string";
    });
}

In this example, the const method is never called.If the code looks weird, here's what I'm trying to do:

Instead of a getter method, I let clients iterate objects by passing a function. To enable both const and non-const access, I want to provide const and non-const overloads. Further, to avoid copy & paste, I want to implement the non-const method in terms of the const method: the const method in my code is actually more complicated than the one I use here.

Now, my questions is this: If you run this code, it will recursively call the non-const function until the stack overflows. I don't understand why the line doStuff([&func](const string *str) in the non-const method calls itself and not the const method.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire