Lambdas,是否需要使用此关键字消除const / non-const成员函数的歧义?

时间:2019-04-24 19:28:18

标签: c++ c++11 lambda compiler-errors this

当我使用MSVC编译该程序时,收到错误消息

  

“示例:: bar对重载函数的歧义调用”

然后,我发现this关键字能够解决该错误。感到惊讶的是,我使用了rextester,发现Clang和GCC都能够在没有this关键字的情况下编译程序。

这是有问题的程序。

#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;
}

我最后要问的是,lambda中是否需要this关键字来区分const和非const成员函数以及MSVC是正确的还是GCC和Clang是正确的。

我正在使用Visual Studio 2017,MSVC的完整版本为191627027

0 个答案:

没有答案