我无法用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;
}
错误信息是:
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); });
^~~~~
将
const auto& x
改为const std::string& x
使程序可以编译将
print(x)
改为this->print(x)
使程序可以编译所有版本都使用Clang (Apple LLVM version 7.3.0 (Clang -703.0.31))编译。
这是一个编译器错误吗?
这是一个已记录的gcc错误,截至2016年8月尚未修复。
我不认为编译器有义务推断被传递给lambda内部的for_each函数的类型,记住这个函数已经被编译,编译器如何知道for_each函数将传递给lambda后传递给lambda ?
我不知道为什么。但解决方案是指定它应该使用哪个打印:std::for_each(std::cbegin(bars_), std::cend(bars_), [this] (const auto& x) { this->print(x); });
用这个来编译。参见:http://coliru.stacked-crooked.com/a/1177b09a3e5863e2