Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 / g++ : std:: qualifier required in lambda, although "using namespace std" is given

I was trying to discover some of the goodies of the new C++11 standard (using g++ 4.6.2). Playing around with lambdas in a an "all_of" algorithm function, I encountered a strange problem with the std:: qualifier.

I am "using" the std namespace as shown at the beginning of the code snippet. This makes the declaration of the pair variable in the for loop well-defined.

However, I tried the same in the lambda argument used in the "all_of" algorithm. I came across several hard-to-understand error messages, before I realized that a full std:: qualified std::pair would work there, but only pair not.

Am I missing an important point? The declaration of the lambda happens in this file, so the namespace should still be active here, right? Or does the required std:: qualifier depend on some STL code in a different file? Or is it likely to be a bug in g++?

Best regards, Peter

PS: the code compiles without warnings as pasted here, but removing the std:: in the all_of lambda, I get an error message.

#include <iostream>
#include <memory>
#include <map>
#include <string>
#include <algorithm>
#include <utility>

using namespace std;

void duckburg() {

const int threshold = 100;
map <string, int> money;

money["donald"] = 200;
money["daisy"] = 400;
money["scrooge"] = 2000000;

// obviously, an "auto" type would work here nicely,
// but this way my problem is illustrated more clearly:

for (const pair <string, int> &pair : money) {
    cout << pair.first << "\t" << pair.second << endl;
}

if (all_of(money.begin(), money.end(),
    [&](std::pair<string, int> p) {
    return bool(p.second > threshold);
})) 
{
    cout << "yes, everyone is rich!";
} else {
    cout << "no, some are poor!";
};
}

Edit: Just noticed I received a downvote for this old question. No problem with that, but please elaborate on the reasons. It will help me improve future questions, and in the end the entire community will profit. Thanks!

like image 620
Piotr99 Avatar asked Dec 16 '11 13:12

Piotr99


1 Answers

Rename the variable pair in your for loop.

It's scope should only extend to the end of the for loop and therefore not interfere with your lambda, but g++ has some code for ancient for-scoping rules where that was not the case, so it can emit better error messages for ancient C++ code.

It looks as if there is a bug in that compatibility code.

like image 107
wolfgang Avatar answered Nov 14 '22 22:11

wolfgang