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

  • As far as I understand, NRVO cannot deal with multiple return paths for multiple named objects et al, and move semantics should make this less of an issue because you can invoke the move constructor anyway. But I'm seeing some confusing results with the CTP when combining move semantics with "regular" RVO.

    This invokes the move constructor (in a debug build without NRVO):

    struct foo

    {

     foo() { std::cout << "foo()\n"; }

     foo(const foo&) { std::cout << "foo(const foo&)\n"; }

     foo(foo&&) { std::cout << "foo(foo&&)\n"; }

    };

    foo test()

    {

     foo f; // avoid RVO

     return f;

    }

    ...

    foo f = test();

    This also invokes the move constructor for both true/false:

    foo test(bool bar)

    {

     if (!bar)

     {

       foo f;

       return f;

     }

     foo g;

     return g;

    }

    ...

    foo f = test(true);

    This, however, uses RVO for return foo(), but copy-constructs f to the caller:

    foo test(bool bar)

    {

     if (!bar)

       return foo();

     foo f;

     return f;

    }

    ...

    foo f = test(true);

    If the compiler decides that it cannot determine RVO, shouldn't it just treat the return path as returning a rvalue that can be move-constructed in the caller by default?

    Furthermore, explicitly stating that the return type is an rvalue works as I would expect:

    foo test(bool bar)

    {

     if (!bar)

       return std::move(foo());

     foo f;

     return std::move(f);

    }

    Is this intended behavior or a compiler oversight? Or am I just way off? :)

  • The four features you have included are fantastic additions (well, at least three of them :)). However, I am slightly disappointed that decltype is not mentioned. Is it not going to be implemented in VC10? If so, why?

    Tor Brede:

    It is also my understanding that the move constructor should be invoked in the case of foo(true).

  • Don't auto and typeof (and decltype) go hand in hand? I've written a large codebase which uses gcc's typeof throughout, and have been hoping and waiting for years now for MSVC to support typeof. gcc's had typeof forever. I don't use MSVC for the single reason of lack of typeof. When I saw that this CTP was out, I was quite excited as I thought auto surely implies typeof. Apparently not.. but why?

  • http://blogs.msdn.com/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10

  • 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.

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

  • @VC++ team - I hope those comments about "us C++ devs feeling second class ... because you don't give us xyz" don't hurt you too much. That is so ungrateful of "those" C++ devs to get new features with every new VC++ version and still the only thing they do is moaning around about "the single most important feature missing".

    @robthablob: whatever you do for others, are you sure that you always give everything in one shot to everybody wanting something from you? Yes? Well then, go on throwing stones.

    --

    SvenC

  • I'd like to answer robthablob.

    Concepts were added to the C++ Working Paper at the very end of the last C++ Standards meeting (which was in July in San Francisco) just before the Working Paper was approved as the first Committee Draft. Before this point Concepts were a "potential" C++-0x feature, now they are, finally, an official C++-0x feature. Concepts are also by far and away the biggest C++-0x feature: my conservative estimate is that it would take me at least 1 year to implement the feature. So there is no way we csould have Concepts ready for Dev10 - there just isn't the time.

  • This makes me very excited for C++0x! Lambda's going to be pretty awesome.

    If I was going to make one complaint it would be that lambda's syntax isn't going to be nice to remember at first. That's one thing about Java that is nice: the syntax is easy, it just feels right. I'd still take C++ for the power any day.

  • [Nikola Smiljanic]

    > Will VC10 support extern templates?

    Actually, my previous answer was bogus. JonCaves informed me that extern templates have been implemented as an extension since Visual C++ 2.0. Like long long, this was a very popular extension (GCC implemented it too), so C++0x is Standardizing it.

    [Julian St.]

    > If you inspect other languages with closures (Standard ML, Haskell, Common Lisp, Ruby, Smalltalk ... whatever),

    > you'll see that closures are a very integral and most of all SIMPLE thing to use.

    > The feature you presented above is more or less the opposite of that.

    This is incorrect. I know Scheme, so I'll use it as an example. Scheme's (lambda (n) (* n n n)) and C++0x's [](int n) { return n * n * n; } are equally simple, after you get past their syntactic flavoring. In fact, C++0x lambdas (and C++ functors in general) have the upper hand, as they make dealing with mutable state easy. Scheme doesn't. I don't know about other functional languages - this is not a general criticism - but Scheme in particular makes dealing with mutable state way too complicated. Scheme's environment model is utterly incomprehensible, while everyone knows how C++ data members work.

    > This new C++ standard has about as much reality as the new Fortran 2003 standard. C++ outlived its usefulness for application development.

    If you want X, for X != C++, you know where to find it.

    [decltype]

    > I am slightly disappointed that decltype is not mentioned. Is it not going to be implemented in VC10? If so, why?

    [Zola Enola]

    > When I saw that this CTP was out, I was quite excited as I thought auto surely implies typeof. Apparently not.. but why?

    Implementing auto doesn't implement decltype (C++0x's name for what was previously called typeof) for free.

    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. We understand that certain features "go together", and that adding complementary features is a good thing in general. As always, customer feedback is a vital resource in forming our plans.

    [robthablob]

    Adding to JonCaves' reply:

    > Once again us C++ developers are feeling like second class citizens.

    Compared to whom? Other languages? They don't have templates, much less concepts. Other compilers? They haven't implemented concepts yet. According to my knowledge, there's only one partial implementation, the highly experimental prototype ConceptGCC (and its own webpage says "The compiler is very, very slow and can be rather unstable.").

    [Tor Brede Vekterli]

    > Is this intended behavior or a compiler oversight?

    This appears to be a bug, thanks for the report. I've filed it in our internal bug tracking system (ID 540754).

  • > We understand that certain features "go together", and that adding

    > complementary features is a good thing in general. As always, customer

    > feedback is a vital resource in forming our plans.

    Then let me formally say that in my opinion, r-value references are only semi-useful without variadic templates (for perfect forwarding), and auto is only semi-useful without decltype. So here's a +1 for variadic templates and decltype. ;-)

  • [Adam Merz]

    > r-value references are only semi-useful without variadic templates (for perfect forwarding)

    Take a look at the implementation of VC9 SP1's <functional>. No one wants variadic templates more than I do. :-)

  • Tor Brede Vekterli: JonCaves has confirmed that you've found a bug. He's already figured out the problem and the fix. Thanks again for reporting it!

  • > n fact, C++0x lambdas (and C++ functors in general) have the upper hand, as they make dealing with mutable state easy. Scheme doesn't.

    I don't understand this one. You can just as well mutate variables in the parent scope of lambda in Scheme as you can in C++ - noone has banned "set!" yet.

  • Oh yes, I'll second that request for variadic templates and decltype. If there would be a choice between those two and concepts (I understand that there isn't, just theoretizing), I would certainly pick the first two. Concepts are cool, but static_assert is "good enough" for simple checking, and those two other things are so immensely useful for any sort of TMP...

  • STL wrote:

    >Implementing auto doesn't implement decltype (C++0x's name for what was previously called typeof) for free

    Thanks for the clarification. I am aware of the differences between the two, and to me, the latter is most useful.

    I am still hoping to see decltype in VC10, especially considering the fact that it has already been implemented in several compilers ( and even more for typeof).

    int19h, I don't see how you can even compare static_assert to concepts :). Implementing concepts also implies providing a fully "conceptualized" standard library, which is a huge change.

Page 3 of 7 (91 items) 12345»