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?
This is a documented gcc bug which as of August 2016 has not been fixed yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With