Something like automaticaly updated varlible

I though this was suppose to result as a function which I would call like t(), but I get this error: 't' dose not name a type. So how do I assign a type to it?

auto t = [&]{return r - (i * u);};
I though this was suppose to result as a function which I would call like t()


It does. The code you posted is correct and works for me.

but I get this error: 't' dose not name a type.


Are you sure your compiler supports C++11?
The code you posted is correct and works for me.



I've yet to dabble in C++11, but, did it really work without defining r, i, and u?
I assumed r, i, and u were defined previously.

This compiles:
1
2
3
4
5
6
7
8
int main()
{
    int r, i, u;

    auto t = [&]{return r - (i * u);};

    t();
}



EDIT:

Oh crap... I just realized the parenthesis are missing, but my compiler is not complaining about that. I wonder if that's standards-legal?

Maybe you have to do this:

1
2
3
4
auto t = [&] () {return r - (i * u);};
             ^
             |
Note the added parenthesis
Last edited on
Apparently wxdev dose not think either is ok.
And I got a virus and had to delete whole C: I now installed cb, but it has some compiler, something is not linked idk what, I'll ask my friend when he gets on skype, so I can't use that.

This is what I'm trying
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
    int i = 3;
    int u = 0;
    int r = 60;
    
    auto t = [&](){return r - (i * u);};
    
    while (t() >= 0)
    {
        cout << t() << endl << u++ << endl;
    }
}
@Disch: if the lambda takes no parameters you may omit the parens - it is part of the standard.

Also, that code works:
http://ideone.com/94zD24 (with parens)
http://ideone.com/LxxDuL (without parens)
Last edited on
LB: Thanks for the clarificiaion.


@ zoran: If you're using C::B, then you're probably using gcc as the compiler. Make sure you enable the -c++11 compiler switch (look around in the compiler/project settings pages in C::B).
How do I enable that switch?

And how dose the computer know what is going to be the return type for this function?
How do I enable that switch?


I don't have C::B installed here so I can't check for myself, but a quick bit of googling suggests it is in the "Project Build Options|Compiler Settings tab from within Code::Blocks."

And how dose the computer know what is going to be the return type for this function?


It can do it automatically, but only for small, simple functions by examining the return statement and seeing what the returned expression evaluates to.

For more complex functions (or if you want to), you can explicitly give the return type:

 
[&] () -> int { return x; }
Last edited on
Topic archived. No new replies allowed.