![](/img/trans.png)
[英]variable cannot be implicitly captured in a lambda with no capture-default specified using a switch statement
[英]Variable cannot be implicitly captured in a lambda with no capture-default specified
我正在關注這篇關於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功能,我當然不知道,這就是我現在在這里的原因。 有人能解釋一下這個問題嗎? 我需要做什么才能正確編譯此代碼?
提前致謝! :)
編輯:原來問題不在於unit或stringify。 讓我粘貼新代碼:
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
我會更多地玩它,如果我修復它,我會在這里發布,但如果你能夠發布你的解決方案或評論。 再次感謝!
你去:
auto unit = [](auto x) {
return [=](){ return x; };
};
auto stringify = [unit](auto x) { // or '&unit
stringstream ss;
ss << x;
return unit(ss.str());
};
Lambda不捕獲任何外部范圍,您必須指定它。
編輯:用戶'TC'是對的 - 這篇文章中的兩個lambdas都是全局的。 在這種情況下,無需指定即可訪問unit
。 並且隨着規范(我給出),它在VC2015中失敗了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.