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& x
以const std::string& x
使程序编译.
更改print(x)
以this->print(x)
使程序编译.
所有版本都使用Clang编译(Apple LLVM版本7.3.0(clang-703.0.31)).
这是编译器错误吗?
The*_*Kid -3
我不认为编译器有义务推断出 for_each 函数内传递给 lambda 的类型,请记住这个函数已经被编译了,编译器如何知道 for_each 函数将在之后传递给 lambda它传递了 lambda 吗?
归档时间: |
|
查看次数: |
649 次 |
最近记录: |