【发布时间】:2015-10-28 18:48:54
【问题描述】:
我正在关注这个人关于 C++ Lambdas http://cpptruths.blogspot.com/2014/03/fun-with-lambdas-c14-style-part-1.html 的博客文章,在编译他的代码时,我遇到了编译器错误:
variable 'unit' cannot be implicitly captured in a lambda with no capture-default specified"
它引用的行如下:
auto unit = [](auto x) {
return [=](){ return x; };
};
auto stringify = [](auto x) {
stringstream ss;
ss << x;
return unit(ss.str());
};
这家伙似乎知道 C++ 中的新 Lambda 功能,而我当然不知道,这就是我现在在这里的原因。有人可以阐明这个问题吗?我需要做什么才能正确编译此代码?
提前致谢! :)
edit:原来问题不在于单元或字符串化。让我粘贴新代码:
auto unit = [](auto x) {
return [=](){ return x; };
};
auto stringify = [unit](auto x) {
stringstream ss;
ss << x;
return unit(ss.str());
};
auto bind = [](auto u) {
return [=](auto callback) {
return callback(u());
};
};
cout << "Left identity: " << stringify(15)() << "==" << bind(unit(15))(stringify)() << endl;
cout << "Right identity: " << stringify(5)() << "==" << bind(stringify(5))(unit)() << endl;
//cout << "Left identity: " << stringify(15)() << endl;
//cout << "Right identity: " << stringify(5)() << endl;
好的,所以,对“绑定”的调用是导致以下错误的原因:
"__ZZZ4mainENK4$_17clINSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEEEDaT_ENUlvE_C1ERKSA_", referenced from:
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > main::$_19::operator()<auto main::$_17::operator()<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) const::'lambda'()>(auto main::$_17::operator()<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) const::'lambda'()) const in funwithlambdas-0f8fc6.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [funwithlambdas] Error 1
我会再尝试一下,如果我修复它,我会在这里发布,但如果可以的话,请发布您的解决方案或评论。再次感谢!
【问题讨论】:
-
他可能是在全局范围内编写的(或者没有测试)。
-
stringify没有办法获得unit.的定义将stringify的默认捕获方法更改为引用,或者仅通过引用捕获unit应该让它编译,虽然这并不能保证正确的行为...... -
@jaggedSpire 谢谢,这确实有帮助。我意识到错误不是来自对 stringify 的调用,而是来自另一个函数。我将使用新代码和错误更新主帖。
-
@MikeBell 我认为你在使用 clang? gcc 编译并链接它,并且 clang 输出与您在 these 设置中给出的相同的错误消息。另外:您是否将 lambdas 移动到
main函数中?您粘贴的代码不清楚。 -
@jaggedSpire 哦,哈哈,我没有意识到我的 g++ 指向的是clang。感谢您的提醒。是的,lambdas 在 main 函数中。一旦我尝试使用 real g++ 进行编译,我会回到这里。