Mik*_*ell 6 c++ macos g++ c++11 c++14
我正在关注这个人关于 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"
Run Code Online (Sandbox Code Playgroud)
它引用的行如下:
auto unit = [](auto x) {
return [=](){ return x; };
};
auto stringify = [](auto x) {
stringstream ss;
ss << x;
return unit(ss.str());
};
Run Code Online (Sandbox Code Playgroud)
这家伙似乎了解 C++ 中的新 Lambda 功能,而我当然不知道,这就是我现在在这里的原因。有人可以阐明这个问题吗?我需要做什么才能正确编译此代码?
提前致谢!:)
编辑:事实证明问题不在于单位或字符串化。让我粘贴新代码:
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;
Run Code Online (Sandbox Code Playgroud)
好的,所以,对“bind”的调用导致了以下错误:
"__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
Run Code Online (Sandbox Code Playgroud)
我会多尝试一下,如果我修复了它,我会在这里发布,但如果可以的话,请发布您的解决方案或评论。再次感谢!
就这样:
auto unit = [](auto x) {
return [=](){ return x; };
};
auto stringify = [unit](auto x) { // or '&unit
stringstream ss;
ss << x;
return unit(ss.str());
};
Run Code Online (Sandbox Code Playgroud)
Lambda 不捕获外部作用域的任何内容,您必须指定它。
编辑:用户“TC”是对的 - 在那篇文章中,两个 lambda 都是全局的。在这种情况下,unit无需指定即可访问。根据规范(我给出的),它在 VC2015 中失败了。
| 归档时间: |
|
| 查看次数: |
17696 次 |
| 最近记录: |