【发布时间】:2014-05-29 21:37:29
【问题描述】:
我想为我的 trie 数据结构实现一个通用的访问者模式。以下是给编译器带来麻烦的提取的最小片段:
#include <functional>
struct Node {
size_t length;
};
template<typename N>
class C {
public:
size_t longest = 0;
std::function<void(const N )> f = [this](N node) {
if(node->length > this->longest) this->longest = node->length;
};
};
int main() {
Node n;
n.length = 5;
C<Node*> c;
c.f(&n);
}
它使用 g++ (Ubuntu/Linaro 4.7.2-2ubuntu1)、Ubuntu clang 版本 3.4-1ubuntu3 和 Apple LLVM 版本 5.0 (clang-500.2.79) 编译。 icc (ICC) 14.0.2 说:
try_lambda_T.cc(15): error: "this" cannot be used inside the body of this lambda
if(node->length > this->longest) this->longest = node->length;
我发现了一个类似的帖子: Class with non-static lambda member can't use default template paramers? 这个故事导致了一个在 g++ 4.8.1 中解决的错误报告: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54764
但是,g++ (Ubuntu 4.8.2-19ubuntu1) 会导致:
internal compiler error: in tsubst_copy, at cp/pt.c:12125
std::function<void(const N )> f = [this](N node) {
^
Please submit a full bug report,
with preprocessed source if appropriate.
我能用它做些什么来让它编译最新的 g++(希望是 icc)?
【问题讨论】:
-
如果您在 lambda 体内使用
longest而不是this->longest,icc 会抱怨吗?您不必说this->,捕获this意味着您可以访问类的数据成员。您发现了一个 gcc 错误(内部编译器错误始终是错误),您应该报告它。 -
我测试了它,
longest而不是this->longest的内部错误相同。g++4.9OS X. -
看起来像一个编译器错误,但是您可以尝试通过引用而不是
this实例捕获longest作为临时解决方法。