gcc无法使用此捕获编译通用lambda

Dan*_*iel 11 c++ lambda gcc this c++14

我无法使用gcc 6.1编译以下程序:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

class Foo
{
public:
    void apply() const
    {
        std::for_each(std::cbegin(bars_), std::cend(bars_), [this] (const auto& x) { print(x); });
    }
private:
    std::vector<std::string> bars_;

    void print(const std::string& x) const
    {
        std::cout << x << ' ';
    }
};

int main()
{
    Foo foo {};
    foo.apply();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误消息是:

error: cannot call member function 'void Foo::print(const string&) const' without object
         std::for_each(std::cbegin(bars_), std::cend(bars_), [this] (const auto& x) { print(x); });
                                                                                      ^~~~~
Run Code Online (Sandbox Code Playgroud)
  • 更改const auto& xconst std::string& x使程序编译.

  • 更改print(x)this->print(x)使程序编译.

  • 所有版本都使用Clang编译(Apple LLVM版本7.3.0(clang-703.0.31)).

这是编译器错误吗?

Tem*_*Rex 5

这是一个记录在案的gcc bug,截至2016年8月还没有修复.


The*_*Kid -3

我不认为编译器有义务推断出 for_each 函数内传递给 lambda 的类型,请记住这个函数已经被编译了,编译器如何知道 for_each 函数将在之后传递给 lambda它传递了 lambda 吗?

  • 编译器使用给定的模板参数实例化“for_each”,然后使用正确的类型实例化 lambda。 (2认同)