mercredi 24 avril 2019

Lambdas, Is this keyword needed to disambiguate const/non-const member functions?

When I use MSVC to compile this program, I receive the error,

"Example::bar ambiguous call to overloaded function"

Then, I found that the this keyword was able to resolve the error. Surprised, I used rextester and found that both Clang and GCC were able to compile the program without the this keyword.

Here is the program in question.

#include <iostream>

class Example {
public:
    Example() {
        auto lambda = [this]() {
            //this->bar<int>(); //  Using this allows the program to compile and run successfully.
            bar<int>(); //   This doesn't work in MSVC
        };
        lambda();
    }

    template<typename T>
    void bar() {
        std::cout << "(non-const) bar\n";
    }

    template<typename t>
    void bar() const {
        std::cout << "(const) bar\n";
    }
};

int main() {
    Example example;
}

Ultimately I am asking, is this keyword needed in a lambda to disambiguate between const and non-const member functions and whether MSVC is correct or GCC and Clang are correct.

Aucun commentaire:

Enregistrer un commentaire