Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc fails to compile generic lambda with this capture [duplicate]

I cannot compile the following program with 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;
}

The error message is:

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); });
                                                                                      ^~~~~
  • Changing const auto& x to const std::string& x makes the program compile.

  • Changing print(x) to this->print(x) makes the program compile.

  • All versions compile with Clang (Apple LLVM version 7.3.0 (clang-703.0.31)).

Is this a compiler bug?

like image 963
Daniel Avatar asked Aug 09 '16 08:08

Daniel


1 Answers

This is a documented gcc bug which as of August 2016 has not been fixed yet.

like image 152
TemplateRex Avatar answered Nov 20 '22 13:11

TemplateRex