Re: invalid use of auto in expression ??
On May 8, 11:33 am, mdcb...@gmail.com wrote:
Hello all,
I was wondering if this was legit C++11x
std::map<std::string, int> m;
...
(1) if ((auto bar = m.find("bar")) == m.end()) std::cout << "bar=
not found\n";
breaking it down in 2 steps keeps my compiler happy:
(2) auto foo = m.find("foo");
if (foo == m.end()) std::cout << "foo not found\n";
Is this guided by the standard, or a limitation with my compiler?
Thanks
I don't have a chapter and verse to cite, but I don't think the above
form (1) is allowed in either C++ 03 or 11 (neither with "auto" nor
with an actual explicit type). This won't compile either:
if ((int foo = getSomeInt()) == 5) { doSomething(foo); }
Perhaps you're thinking of this form, which is slightly less
featureful but does compile:
if (int foo = getSomeInt()) { doSomething(foo); }
This calls doSomething(foo) if a boolean conversion of the value
assigned to foo from getSomeInt() is true. It's a nice replacement
for
int foo = getSomeInt();
if (foo) { doSomething(foo); }
which keeps the scope of foo better-contained.
So I'd imagine that the following should work in C++ 11 (not tested)
if (auto foo = getSomething()) { doSomething(foo); }
This doesn't help with your particular example, though. On the other
hand, your example isn't using the value of 'bar' anyway, so you could
simply use
if (m.find("bar") == m.end()) std::cout << "bar not found\n";
- Kevin B. McCarty