在未指定捕获默认值的情况下,无法在 lambda 中隐式捕获变量[重复]

问题描述 投票:0回答:1

我正在关注这个人关于 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 新功能,而我当然不知道,这就是我现在在这里的原因。有人可以阐明这个问题吗?我需要做什么才能正确编译此代码?

提前致谢! :)


编辑:事实证明问题不在于单位或字符串化。让我粘贴新代码:

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;

好的,所以,调用“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

我会多尝试一下,如果我修复了它,我会在这里发布,但如果可以的话,请发布您的解决方案或评论。再次感谢!

c++ macos c++11 g++ c++14
1个回答
3
投票

就这样:

auto unit = [](auto x) {
    return [=](){ return x; };
};
auto stringify = [unit](auto x) { // or '&unit
    stringstream ss;
    ss << x;
    return unit(ss.str());
};

Lambda 不捕获外部范围的任何内容,您必须指定它。

编辑:用户“T.C.”是对的 - 在那篇文章中,两个 lambda 表达式都是全局的。在这种情况下,无需指定即可访问

unit
。并且按照规范(我给出的),它在 VC2015 中失败了。

© www.soinside.com 2019 - 2024. All rights reserved.