Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1

Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1

Rate This
  • Comments 91

The Visual C++ compiler in the Microsoft Visual Studio 2010 September Community Technology Preview (CTP) contains support for four C++0x language features, namely lambdas, auto, static_assert, and rvalue references.  Today, I'm going to explain the first three features in detail.  (And I'm going to dedicate an entire post to explaining rvalue references in the near future, simply because explaining them now would double the length of this already very long post.)

 

First, a few quick things:

 

1. Today's post is brought to you by Stephan T. Lavavej, Visual C++ Libraries Developer, and the letters C, A, and T.  Note that as a libraries dev, I didn't implement these features.  That was the work of Jonathan Caves, front-end compiler dev, voting Standardization Committee member, and all-around ninja.

 

2. I refer to the Visual C++ compiler in VS 2010 as VC10 (VS 2008 contained VC9, VS 2005 contained VC8, etc. - 10 is not short for 2010).

 

3. C++0x refers to the upcoming C++ Standard, which is still being drafted.  (The Standardization Committee hopes that they'll be finished in 2009, making it C++09; the joke is that if it slips to 2010 or later, the 'x' will be hexadecimal.)  C++98 and C++03 refer to the current C++ Standard.  (Without going into a history lecture here, the 2003 C++ Standard was merely a "service pack" for the original 1998 C++ Standard, and most people can disregard the differences.  C++03 and C++0x are totally different, despite appearances.)

 

4. I'd like to thank the Standardization Committee for developing these wonderfully useful and well-crafted features.  They also make important documents available on their website:

 

C++0x language feature status: http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2705.html

C++0x library feature status: http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2706.html

C++0x Working Draft: http://open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2798.pdf

 

5. There are always bugs (although hopefully not too many), which is the whole point of the CTP.  Please report bugs to us via Microsoft Connect.

 

Now, let's look at the features!

 

 

lambdas

In C++0x, "lambda expressions" implicitly define and construct unnamed function objects, which then behave like handwritten function objects.  This is the "Hello, World" lambda:

 

C:\Temp>type meow.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 meow.cpp > NUL && meow

0 1 2 3 4 5 6 7 8 9

 

The [] is the lambda-introducer, which tells the compiler that a lambda expression is beginning.  The (int n) is the lambda-parameter-declaration, which tells the compiler what the unnamed function object class's function call operator should take.  Finally, the { cout << n << " "; } is the compound-statement which serves as the body of the unnamed function object class's function call operator.  By default, the unnamed function object class's function call operator returns void.

 

 

So, C++0x has mentally translated this into what you'd write in C++98:

 

C:\Temp>type meow98.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

struct LambdaFunctor {

    void operator()(int n) const {

        cout << n << " ";

    }

};

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    for_each(v.begin(), v.end(), LambdaFunctor());

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 meow98.cpp > NUL && meow98

0 1 2 3 4 5 6 7 8 9

 

Now I'm going to stop saying things like "the unnamed function object class's function call operator returns void" and start saying "the lambda returns void", but it's important to remember what lambda expressions are doing: defining classes and constructing objects.

 

 

Of course, the compound-statement of a lambda can contain multiple statements:

 

C:\Temp>type multimeow.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    for_each(v.begin(), v.end(), [](int n) {

        cout << n;

 

        if (n % 2 == 0) {

            cout << " even ";

        } else {

            cout << " odd ";

        }

    });

 

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 multimeow.cpp > NUL && multimeow

0 even 1 odd 2 even 3 odd 4 even 5 odd 6 even 7 odd 8 even 9 odd

 

 

Now, lambdas don't always have to return void.  If a lambda's compound-statement is { return expression; } , then the lambda's return type will be automatically deduced to be the type of expression:

 

C:\Temp>type cubicmeow.cpp

#include <algorithm>

#include <deque>

#include <iostream>

#include <iterator>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    deque<int> d;

 

    transform(v.begin(), v.end(), front_inserter(d), [](int n) { return n * n * n; });

 

    for_each(d.begin(), d.end(), [](int n) { cout << n << " "; });

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 cubicmeow.cpp > NUL && cubicmeow

729 512 343 216 125 64 27 8 1 0

 

Here, the type of n * n * n is int, so this lambda's function call operator returns int.

 

 

Lambdas with more complicated compound-statements don't get automatically deduced return types.  You have to explicitly specify them:

 

C:\Temp>type returnmeow.cpp

#include <algorithm>

#include <deque>

#include <iostream>

#include <iterator>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    deque<double> d;

 

    transform(v.begin(), v.end(), front_inserter(d), [](int n) -> double {

        if (n % 2 == 0) {

            return n * n * n;

        } else {

            return n / 2.0;

        }

    });

 

    for_each(d.begin(), d.end(), [](double x) { cout << x << " "; });

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 returnmeow.cpp > NUL && returnmeow

4.5 512 3.5 216 2.5 64 1.5 8 0.5 0

 

The -> double is the optional lambda-return-type-clause.  Why doesn't it go on the left, like what programmers have been doing with C functions for longer than I've been alive?  Because then the lambda-introducer wouldn't come first, and that's what tells the compiler that a lambda expression is beginning.  (Figuring out this kind of stuff is what the Core Working Group excels at; trying to imagine whether a given construct would be parseable within C++ hurts my head.)

 

 

If you forget the lambda-return-type-clause, the compiler will complain about each return statement:

 

C:\Temp>cl /EHsc /nologo /W4 borkedreturnmeow.cpp

borkedreturnmeow.cpp

borkedreturnmeow.cpp(20) : error C3499: a lambda that has been specified to have a void return type cannot return a value

borkedreturnmeow.cpp(22) : error C3499: a lambda that has been specified to have a void return type cannot return a value

 

 

All of the lambdas I've presented so far have been stateless: they contain no data members.  You can have stateful lambdas too, and this is accomplished through "capturing" local variables.  The empty lambda-introducer [] says "I am a stateless lambda".  But within the lambda-introducer, you can specify a capture-list:

 

C:\Temp>type capturekittybyvalue.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 0;

    int y = 0;

 

    // op>>() leaves newlines on the input stream,

    // which can be extremely confusing. I recommend

    // avoiding it, and instead using non-member

    // getline(cin, str) to read whole lines and

    // then parse them. But in the interests of

    // brevity, I'll use evil op>>():

 

    cout << "Input: ";

    cin >> x >> y;

 

    v.erase(remove_if(v.begin(), v.end(), [x, y](int n) { return x < n && n < y; }), v.end());

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 capturekittybyvalue.cpp > NUL && capturekittybyvalue

Input: 4 7

0 1 2 3 4 7 8 9

 

 

If you forget the capture-list, the compiler will complain:

 

C:\Temp>cl /EHsc /nologo /W4 borkedcapturekittybyvalue.cpp

borkedcapturekittybyvalue.cpp

borkedcapturekittybyvalue.cpp(27) : error C3493: 'x' cannot be implicitly captured as no default capture mode has been specified

borkedcapturekittybyvalue.cpp(27) : error C3493: 'y' cannot be implicitly captured as no default capture mode has been specified

 

(I'll explain default captures soon.)

 

Remember, the lambda expression is implicitly defining an unnamed function object class.  The compound-statement { return x < n && n < y; } serves as the body of the function call operator within that class.  Although the compound-statement is lexically within the scope of main(), it is conceptually outside the scope of main(), so you can't use local variables from main() without capturing them within the lambda.

 

 

Here's what this is being mentally translated into:

 

C:\Temp>type capturekittybyvalue98.cpp

#include <algorithm>

#include <iostream>

#include <iterator>

#include <ostream>

#include <vector>

using namespace std;

 

class LambdaFunctor {

public:

    LambdaFunctor(int a, int b) : m_a(a), m_b(b) { }

 

    bool operator()(int n) const { return m_a < n && n < m_b; }

 

private:

    int m_a;

    int m_b;

};

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 0;

    int y = 0;

 

    cout << "Input: ";

    cin >> x >> y; // EVIL!

 

    v.erase(remove_if(v.begin(), v.end(), LambdaFunctor(x, y)), v.end());

 

    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 capturekittybyvalue98.cpp > NUL && capturekittybyvalue98

Input: 4 7

0 1 2 3 4 7 8 9

 

Here, you can clearly see that the captures are "by value".  Copies of the local variables are being stored within the function object.  This allows the function object to outlive the local variables that were captured to create it.  However, note that (a) the captured copies can't be modified within the lambda, because by default the function call operator is const, (b) some objects are expensive to copy, and (c) updates to the local variables will not be reflected in the captured copies (these are ordinary value semantics).  Soon, I'll explain how to deal with each of these when necessary.

 

 

But first, instead of specifying every local variable that you want to capture, you can say "capture everything by value".  The syntax for this is the lambda-introducer [=] (the capture-default = is supposed to make you think of assignment or copy-initialization Foo foo = bar; , although the copies are actually made by direct-initialization, like m_a(a) above):

 

C:\Temp>type defaultcapturekittybyvalue.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 0;

    int y = 0;

 

    cout << "Input: ";

    cin >> x >> y; // EVIL!

 

    v.erase(remove_if(v.begin(), v.end(), [=](int n) { return x < n && n < y; }), v.end());

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 defaultcapturekittybyvalue.cpp > NUL && defaultcapturekittybyvalue

Input: 4 7

0 1 2 3 4 7 8 9

 

When the compiler sees x and y mentioned within the lambda, it captures them from main() by value.

 

 

What about (a), modifying the captured copies?  By default, a lambda's function call operator is const, but you can make it non-const by saying mutable:

 

C:\Temp>type capturekittybymutablevalue.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 1;

    int y = 1;

 

    for_each(v.begin(), v.end(), [=](int& r) mutable {

        const int old = r;

 

        r *= x * y;

 

        x = y;

        y = old;

    });

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

 

    cout << x << ", " << y << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 capturekittybymutablevalue.cpp > NUL && capturekittybymutablevalue

0 0 0 6 24 60 120 210 336 504

1, 1

 

This multiplies each element of v by the previous two elements.  (I had to think really hard to come up with an example that couldn't be expressed with partial_sum(), which could multiply by all previous elements, or adjacent_difference(), which could multiply by the immediately previous element.)  Note that (d) updates to the captured copies are not reflected in the local variables (again, ordinary value semantics).

 

 

What if you want to deal with (b), (c), and (d): avoid copies, observe updates to the local variables from within the lambda, and modify the local variables from within the lambda?  In that case, you want to capture by reference.  The syntax for doing this is the lambda-introducer [&x, &y] (you should think of this as X& x, Y& y ; that is, "reference" and not "address of"):

 

C:\Temp>type capturekittybyreference.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 1;

    int y = 1;

 

    for_each(v.begin(), v.end(), [&x, &y](int& r) {

        const int old = r;

 

        r *= x * y;

 

        x = y;

        y = old;

    });

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

 

    cout << x << ", " << y << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 capturekittybyreference.cpp > NUL && capturekittybyreference

0 0 0 6 24 60 120 210 336 504

8, 9

 

Note the differences from capturekittybymutablevalue.cpp: (1) the lambda-introducer [&x, &y] , (2) the absence of mutable , and (3) the local variables x and y having values of 8 and 9 at the end, reflecting their modification within the lambda.

 

 

This is being mentally translated into:

 

C:\Temp>type capturekittybyreference98.cpp

#include <algorithm>

#include <iostream>

#include <iterator>

#include <ostream>

#include <vector>

using namespace std;

 

#pragma warning(push)

#pragma warning(disable: 4512) // assignment operator could not be generated

 

class LambdaFunctor {

public:

    LambdaFunctor(int& a, int& b) : m_a(a), m_b(b) { }

 

    void operator()(int& r) const {

        const int old = r;

 

        r *= m_a * m_b;

 

        m_a = m_b;

        m_b = old;

    }

 

private:

    int& m_a;

    int& m_b;

};

 

#pragma warning(pop)

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int x = 1;

    int y = 1;

 

    for_each(v.begin(), v.end(), LambdaFunctor(x, y));

 

    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

    cout << endl;

 

    cout << x << ", " << y << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 capturekittybyreference98.cpp > NUL && capturekittybyreference98

0 0 0 6 24 60 120 210 336 504

8, 9

 

(When you use lambdas, the compiler automatically disables warning C4512 for lambda definitions.)

 

 

When you capture local variables by reference, the function object stores reference data members to those local variables.  This avoids copying, allows the function object to observe updates to those local variables, and allows the function object to modify those local variables through its references.  (Note that the function call operator is const, because we didn't say mutable, but that just prevents us from modifying the function object's data members.  The data members here are references and can't be modified anyways, but they can be used to modify what they refer to.  The constness of the function call operator is shallow, as always.)

 

Of course, if a lambda function object outlives local variables that it has captured by reference, you get crashtrocity.

 

 

Again, you can use default captures; the lambda-introducer [&] says "capture everything by reference".

 

What if you want to mix value captures and reference captures?  You could say [a, b, c, &d, e, &f, g] .  But you can also specify a capture-default and then override it for specific local variables.  Here's an example, modified from capturekittybymutablevalue.cpp:

 

C:\Temp>type overridekitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    int sum = 0;

    int product = 1;

 

    int x = 1;

    int y = 1;

 

    for_each(v.begin(), v.end(), [=, &sum, &product](int& r) mutable {

        sum += r;

 

        if (r != 0) {

            product *= r;

        }

 

        const int old = r;

 

        r *= x * y;

 

        x = y;

        y = old;

    });

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

 

    cout << "sum: " << sum << ", product: " << product << endl;

    cout << "x: " << x << ", y: " << y << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 overridekitty.cpp && overridekitty

overridekitty.cpp

0 0 0 6 24 60 120 210 336 504

sum: 45, product: 362880

x: 1, y: 1

 

Here, we want to capture x and y by value (because we want to modify them within the lambda, but not outside), while we want to capture sum and product by reference (because we do want to modify them outside).  The opposite lambda-introducer [&, x, y] would produce exactly the same result (capture everything by reference, except x and y by value).

 

 

Now, what if you want to do this?

 

C:\Temp>type memberkitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

class Kitty {

public:

    explicit Kitty(int toys) : m_toys(toys) { }

 

    void meow(const vector<int>& v) const {

        for_each(v.begin(), v.end(), [m_toys](int n) {

            cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;

        });

    }

 

private:

    int m_toys;

};

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 3; ++i) {

        v.push_back(i);

    }

 

    Kitty k(5);

    k.meow(v);

}

 

C:\Temp>cl /EHsc /nologo /W4 memberkitty.cpp

memberkitty.cpp

memberkitty.cpp(12) : error C3480: 'Kitty::m_toys': a lambda capture variable must be from an enclosing function scope

 

 

The lambda expression syntax allows you to capture local variables, but data members aren't local variables.  By special dispensation, you can also capture this:

 

C:\Temp>type workingmemberkitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

class Kitty {

public:

    explicit Kitty(int toys) : m_toys(toys) { }

 

    void meow(const vector<int>& v) const {

        for_each(v.begin(), v.end(), [this](int n) {

            cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;

        });

    }

 

private:

    int m_toys;

};

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 3; ++i) {

        v.push_back(i);

    }

 

    Kitty k(5);

    k.meow(v);

}

 

C:\Temp>cl /EHsc /nologo /W4 workingmemberkitty.cpp > NUL && workingmemberkitty

If you gave me 0 toys, I would have 5 toys total.

If you gave me 1 toys, I would have 6 toys total.

If you gave me 2 toys, I would have 7 toys total.

 

When you've captured this, you can say m_toys, which implicitly means this->m_toys as usual.  You could explicitly say this->m_toys too.  (Within a lambda expression, you can say this only if you've captured it; you can never get the this pointer for the lambda object itself.)

 

 

You can also capture this implicitly:

 

C:\Temp>type implicitmemberkitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

class Kitty {

public:

    explicit Kitty(int toys) : m_toys(toys) { }

 

    void meow(const vector<int>& v) const {

        for_each(v.begin(), v.end(), [=](int n) {

            cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;

        });

    }

 

private:

    int m_toys;

};

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 3; ++i) {

        v.push_back(i);

    }

 

    Kitty k(5);

    k.meow(v);

}

 

C:\Temp>cl /EHsc /nologo /W4 implicitmemberkitty.cpp > NUL && implicitmemberkitty

If you gave me 0 toys, I would have 5 toys total.

If you gave me 1 toys, I would have 6 toys total.

If you gave me 2 toys, I would have 7 toys total.

 

You can also say [&] , but it doesn't affect how this is captured (always by value).  You can't say [&this] .

 

 

If you want a nullary lambda (taking no arguments), you can elide the lambda-parameter-declaration entirely:

 

C:\Temp>type nullarykitty.cpp

#include <algorithm>

#include <iostream>

#include <iterator>

#include <ostream>

#include <vector>

using namespace std;

 

int main() {

    vector<int> v;

 

    int i = 0;

 

    generate_n(back_inserter(v), 10, [&] { return i++; });

 

    for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });

    cout << endl;

 

    cout << "i: " << i << endl;

}

 

C:\Temp>cl /EHsc /nologo /W4 nullarykitty.cpp > NUL && nullarykitty

0 1 2 3 4 5 6 7 8 9

i: 10

 

This is two characters shorter than [&]() { return i++; } .  Whether eliding the lambda-parameter-declaration is good style is up to you to decide.

 

 

For laughs, this means that the following is valid C++0x:

 

C:\Temp>type nokitty.cpp

int main() {

    [](){}();

    []{}();

}

 

This constructs two do-nothing lambdas (one with a lambda-parameter-declaration, one without) and immediately calls them (that's the final set of empty parentheses).

 

 

Note that the optional lambda-parameter-declaration syntactically consists of:

 

( lambda-parameter-declaration-listopt ) mutableopt exception-specificationopt lambda-return-type-clauseopt

 

So, if you want to say mutable or -> ReturnType, you need empty parentheses between that and the lambda-introducer.

 

 

Finally, because lambdas produce ordinary function objects, you can store them in tr1::function:

 

C:\Temp>type tr1kitty.cpp

#include <algorithm>

#include <functional>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

using namespace std::tr1;

 

void meow(const vector<int>& v, const function<void (int)>& f) {

    for_each(v.begin(), v.end(), f);

    cout << endl;

}

 

int main() {

    vector<int> v;

 

    for (int i = 0; i < 10; ++i) {

        v.push_back(i);

    }

 

    meow(v, [](int n) { cout << n << " "; });

    meow(v, [](int n) { cout << n * n << " "; });

 

    function<void (int)> g = [](int n) { cout << n * n * n << " "; };

 

    meow(v, g);

}

 

C:\Temp>cl /EHsc /nologo /W4 tr1kitty.cpp > NUL && tr1kitty

0 1 2 3 4 5 6 7 8 9

0 1 4 9 16 25 36 49 64 81

0 1 8 27 64 125 216 343 512 729

 

 

auto

 

The auto keyword from C++98, where it did absolutely nothing, has been repurposed in C++0x for automatic type deduction.  When used in a declaration, it says "make the type of this thing the same as the type of whatever initializes it".  Behold:

 

C:\Temp>type autocat.cpp

#include <iostream>

#include <map>

#include <ostream>

#include <regex>

#include <string>

using namespace std;

using namespace std::tr1;

 

int main() {

    map<string, string> m;

 

    const regex r("(\\w+) (\\w+)");

 

    for (string s; getline(cin, s); ) {

        smatch results;

 

        if (regex_match(s, results, r)) {

            m[results[1]] = results[2];

        }

    }

 

    for (auto i = m.begin(); i != m.end(); ++i) {

        cout << i->second << " are " << i->first << endl;

    }

}

 

C:\Temp>cl /EHsc /nologo /W4 autocat.cpp > NUL && autocat

cute kittens

ugly puppies

evil goblins

^Z

kittens are cute

goblins are evil

puppies are ugly

 

map<string, string>::iterator, your decade-long reign of terror has come to an end!

 

(Note that m.begin() returns iterator, not const_iterator, because the map is not const.  C++0x cbegin() allows you to request a const_iterator from a non-const container.)

 

 

lambdas and auto

 

Earlier, I mentioned storing lambdas in tr1::functions.  But you shouldn't do that unless it's necessary, as tr1::function has some overhead.  If you want to reuse a lambda, or simply want to give it a name, you can use auto.  Here's an example, which also does something neat:

 

C:\Temp>type autolambdakitty.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

template <typename T, typename Predicate> void keep_if(vector<T>& v, Predicate pred) {

    auto notpred = [&](const T& t) {

        return !pred(t);

    };

 

    v.erase(remove_if(v.begin(), v.end(), notpred), v.end());

}

 

template <typename Container> void print(const Container& c) {

    for_each(c.begin(), c.end(), [](const typename Container::value_type& e) { cout << e << " "; });

    cout << endl;

}

 

int main() {

    vector<int> a;

 

    for (int i = 0; i < 100; ++i) {

        a.push_back(i);

    }

 

    vector<int> b;

 

    for (int i = 100; i < 200; ++i) {

        b.push_back(i);

    }

 

    auto prime = [](const int n) -> bool {

        if (n < 2) {

            return false;

        }

 

        for (int i = 2; i <= n / i; ++i) {

            if (n % i == 0) {

                return false;

            }

        }

 

        return true;

    };

 

    keep_if(a, prime);

    keep_if(b, prime);

 

    print(a);

    print(b);

}

 

C:\Temp>cl /EHsc /nologo /W4 autolambdakitty.cpp

autolambdakitty.cpp

 

C:\Temp>autolambdakitty

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

 

notpred is a negator lambda!  Note that we can't use C++98 <functional>'s not1(), as that requires your predicate to derive from unary_function, and lambdas don't.

 

 

static_assert

 

static_assert allows you to trigger compiler errors with custom error messages:

 

C:\Temp>type staticfluffykitten.cpp

template <int N> struct Kitten {

    static_assert(N < 2, "Kitten<N> requires N < 2.");

};

 

int main() {

    Kitten<1> peppermint;

 

    Kitten<3> jazz;

}

 

C:\Temp>cl /EHsc /nologo /W4 staticfluffykitten.cpp

staticfluffykitten.cpp

staticfluffykitten.cpp(2) : error C2338: Kitten<N> requires N < 2.

        staticfluffykitten.cpp(8) : see reference to class template instantiation 'Kitten<N>' being compiled

        with

        [

            N=3

        ]

 

 

If you have any questions, I'll be happy to answer them in the Comments.

 

Stephan T. Lavavej

Visual C++ Libraries Developer

  • > int19h, I don't see how you can even compare static_assert to concepts :)

    I'm not. I'm just saying that static_assert does cover one particularly common request, which is to get meaningful error messages on errorneous template instantiations.

  • "Well, I can kind of see why, but I think missing Concepts means that you have no real C++/0x support - that's the single most important new feature."

    True, but I think it'd be silly to have expected C++0x support from VC10. I don't know when they expect to ship VC10, but assuming they keep the trend of shipping early relative to the year it's named after, we'll see VC10 at some point in 2009. And C++0x is only *barely* going to make it in 2009, so at best, VC10 could implement a draft version, but certainly not the final one. It was never realistic to expect a complete C++0x implementation so soon.

    "Once again us C++ developers are feeling like second class citizens. Maybe it's time to jump ship..."

    Why, exactly? Because they give us *some* new features before the standard is finalized? Unlike C#, C++ isn't defined by the people writing the compiler. In C#, people can say "wouldn't it be cool to add feature X", implement X in the next version of the compiler, and then add it to the C# spec.

    C++ works the opposite way. A committee decides on the language features *first*, and then compiler writers try to catch up. (Of course the compiler vendors are represented in the standards committee, but the point is that the features go in the standard spec *first*, and *then* in compilers)

    I'll feel C++ is given a second-class treatment if they don't have a decent C++0x implementation in VC11. But I can't blame them for keeping VC10 mainly a C++03 implementation.

    Anyway, good to hear that there's more c++0x to come in VC10. I got the impression from first reading the post that this was it, these were the 0x features that would be in VC10.

  • > I got the impression from first reading the post that this was it, these were the 0x features that would be in VC10.

    See Stephan's post above, particularly:

    "Paraphrasing our libraries and compiler front-end program manager Damien Watkins, the CTP is only the first look at our VC10 functionality and there is definitely more to come."

  • i just have one thing to say, disappointed about lack of typeof

  • In case you haven't noticed yet, "decltype" was the only feature about which it was not said plainly, "no, it won't be there in VC10".

    So cross your fingers :)

  • One other question regarding lambdas: how well do they play together with C++/CLI? Particularly, can they capture:

    1. Managed handles, either by value or by reference.

    2. Tracking references.

    Also, is there a plan to provide some easy way to make a delegate instance out of a lambda?

  • Well, first of all, lambdas in C++ means that LINQ is now possible. So the question is, on the C++/CLI  are you implementing this?

    Apart from that, I think the biggest thing which I would really like is the intellisense updates, its not as bad now processor usage wise, but it is unable to do anything useful.

  • > Well, first of all, lambdas in C++ means that LINQ is now possible.

    No, it doesn't. C++0x lambdas are not the same as C# 3.0 lambdas (particularly as far as lifetime is concerned). Also, for LINQ, lambdas alone are not sufficient - you actually need "expression trees". And C++0x lambdas cannot be faithfully transformed to expression trees for a number of reasons, from what I can see.

    Like I said above, it is possible to write a simple wrapper function that takes a C++ lambda, and gives you a delegate of any type that might be needed. This will work for LINQ to Objects/XML/DataSet (and any other that doesn't deal with expression trees).

  • "For laughs, this means that the following is valid C++0x:

    int main() {

       [](){}();

       []{}();

    }

    "

    See, this is one thing I dislike about the C++ standards committee: They joke too much. For example, there's the infamous warning in C++2003 that template specializations suck, don't use them, but phrased as a limerick. And now they've decided that wouldn't it be cute if any balanced sequence of empty braces were acceptable by the parser?

    (Okay, not "any" sequence, but {{}}[]{[](){}}([](){}()); is acceptable, for example. For any given line noise, it's getting harder and harder for a human to determine whether it's valid C++.)

    The committee should have ruled that a lambda's body must contain at least one statement, and that an empty parameter-list must not be dropped. Also, they should not have allowed type inference in the one special case you mentioned (the case in which the lambda's body contains only a return statement) --- they should have ruled either that type inference always happened, or that it never happens.

  • The committee is just trying to ensure that there will never such thing as IOCCC for C++ - because it's going to be too easy ;)

  • The lambdas for C++ itself may be different, but since the syntax itself has been formalised then is there anything stopping them from twiddling it a bit and getting them to work as needed under C++/CLI.

    Don't forget, C++ classes are different from the managed classes, but they kept the syntax similar but added what it needed to support the managed classes.

  • [int19h]

    > One other question regarding lambdas: how well do they play together with C++/CLI?

    I don't know anything about managed code, but I've forwarded your question to JonCaves.

    [Anonymous Cowherd]

    > "For laughs, this means that the following is valid C++0x: ..."

    > See, this is one thing I dislike about the C++ standards committee: They joke too much.

    That was my joke, not the Committee's. (I'm not a Committee member.) Sometimes my silliness doesn't involve cats, you know.

    > For example, there's the infamous warning in C++2003 that template specializations suck, don't use them, but phrased as a limerick.

    That's incorrect. Template specializations (both explicit and partial) are extremely powerful and easily usable. The warning is:

    "When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation." (C++03 14.7.3/7)

    This means that you have to ensure that a specialization is declared before it's used, which is easy unless you're doing something excessively tricky.

    > And now they've decided that wouldn't it be cute if any balanced sequence of empty braces were acceptable by the parser?

    That's incorrect. This "falls out" of the grammar; it's not some intentionally cute thing.

    > The committee should have ruled that a lambda's body must contain at least one statement

    That would require *additional* Standardese, because empty compound-statements are perfectly valid. It's also inconsistent, because named functions can have empty bodies.

    > and that an empty parameter-list must not be dropped.

    That would be as simple as removing the opt subscript from lambda-parameter-declaration in the definition of lambda-expression.

    Someone considered making the lambda-parameter-declaration optional to be a useful feature. As I explained in my post, "Whether eliding the lambda-parameter-declaration is good style is up to you to decide."

    > Also, they should not have allowed type inference in the one special case you mentioned

    > (the case in which the lambda's body contains only a return statement) --- they should

    > have ruled either that type inference always happened, or that it never happens.

    Making the lambda-return-type-clause mandatory would produce needless verbosity (the very thing that lambdas are trying to reduce), especially given that a lot of lambdas are going to return bool. But there are real problems with always performing automatic type deduction; in particular, when there are multiple return statements returning different types. (This is easier to encounter than it sounds, especially given the usual arithmetic conversions.) Making the lambda-return-type-clause optional when and only when the lambda's body is a single return statement is a simple and effective rule, easy to learn and remember.

    If you want to make all of your lambda return types explicit, you're certainly welcome to.

  • int19h: JonCaves says:

    You can only pass a variable with a managed type as an argument to a lambda - you can't capture a variable that has a managed type.

    We have no plans to "merge" lambdas and delegates.

  • > You can only pass a variable with a managed type as an argument to a lambda - you can't capture a variable that has a managed type.

    Yep, just tried that myself. "Error C3498: 's': you cannot capture a variable that has a managed type".

    I can't understand why it is the case, though. I can understand why it's not possible to capture managed references - and C# lambdas cannot capture them for the same reason. I can also understand why it's tricky to capture an object handle by value (though if there would be some extension syntax to force the function object created from the lambda to be a "value class", it could work). But there's no reason why I can't capture an object handle by reference! I mean, I can write this:

    struct handwritten_lambda

    {

    String^& s;

    handwritten_lambda(String^& s)

    : s(s)

    {

    }

       void operator() (int x)

    {

           s += x.ToString();

    }

    };

    and then use it:

           std::vector<int> v;

           v.push_back(123);

    String^ s = "Foo";

    std::for_each(

    v.begin(),

    v.end(),

                   handwritten_lambda(s));

    and it works, as expected! But, I cannot write this:

    std::for_each(

    v.begin(),

    v.end(),

    [&s](int x) { s += x.ToString(); });

    Why? Given that C++0x lambdas essentially do the same, they should not have any restrictions on top of what the plain transformation to a function object as described in the standard has.

  • By the way, I have just noticed that function objects generated from lambdas do not have "result_type" typedef, and therefore std::tr1::result_of cannot be applied to them. Looking at the wording of the Standard, it seems that it does not require the lambdas to provide result_type either... is this a Committee oversight, or is it deliberate? If the latter, then what is the suggested workaround?

Page 4 of 7 (91 items) «23456»