August 2013

Quick Q: Why do I have to write 'mutable' on a lambda? -- StackOverflow

Inquiring minds want to know:

Why does C++0x's lambda require “mutable” keyword for capture-by-value, by default?

Short example:

#include <iostream>

int main()
{
    int n;
    [&](){n = 10;}();             // OK
    [=]() mutable {n = 20;}();    // OK
    // [=](){n = 10;}();          // Error: a by-value capture cannot be modified in a non-mutable lambda
    std::cout << n << "\n";       // "10"
}

The question: Why do we need the mutable keyword? It's quite different from traditional parameter passing to named functions. What's the rationale behind?

I was under the impression that the whole point of capture-by-value is to allow the user to change the temporary -- otherwise I'm almost always better off using capture-by-reference, aren't I?

Any enlightenments?

(I'm using MSVC2010 by the way. AFAIK this should be standard)

Quick Q: Where do I have to write 'template' and 'typename'? -- StackOverflow

This question is an oldie but goodie. Note that in C++11 some of this becomes clearer, because it's now recommended to use constexpr and using template aliases instead of "traits" styles, and traits are one of the bigger (but not only) reasons to have a template refer to another template.

Where and why do I have to put the “template” and “typename” keywords?

In templates, where and why do I have to put typename and template on dependent names? What exactly are dependent names anyway? I have the following code: ...