Nested lambda's and 'this' pointers

Nested lambda's and 'this' pointers

C:\Temp>type meow.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

class Foo {

public:

    explicit Foo(const int x) : m_x(x) { }

 

    void mult(vector<vector<int>>& outer) const {

        for_each(outer.begin(), outer.end(), [&](vector<int>& inner) {

            for_each(inner.begin(), inner.end(), [&](int& elem) {

                elem *= m_x;

            });

        });

    }

 

private:

    int m_x;

};

 

int main() {

    Foo f(1000);

 

    vector<vector<int>> v(3, vector<int>(4));

 

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

        for (int j = 0; j < 4; ++j) {

            v[i][j] = i * 10 + j;

        }

    }

 

    f.mult(v);

 

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

        for (int j = 0; j < 4; ++j) {

            cout << v[i][j] << " ";

        }

 

        cout << endl;

    }

}

 

C:\Temp>cl

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 17.00.40309 for 80x86

Copyright (C) Microsoft Corporation.  All rights reserved.

 

usage: cl [ option... ] filename... [ /link linkoption... ]

 

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

meow.cpp

meow.cpp(14) : error C3494: 'this' cannot be captured in a nested lambda

meow.cpp(14) : error C2065: 'm_x' : undeclared identifier

meow.cpp(14) : error C2065: 'm_x' : undeclared identifier

 

C:\Temp>g++ -Wall -Wextra -std=c++0x meow.cpp -o meow.exe

 

C:\Temp>meow

0 1000 2000 3000

10000 11000 12000 13000

20000 21000 22000 23000

 

There's a workaround:

 

C:\Temp>type meow.cpp

#include <algorithm>

#include <iostream>

#include <ostream>

#include <vector>

using namespace std;

 

class Foo {

public:

    explicit Foo(const int x) : m_x(x) { }

 

    void mult(vector<vector<int>>& outer) const {

        const Foo * const myself = this;

 

        for_each(outer.begin(), outer.end(), [&](vector<int>& inner) {

            for_each(inner.begin(), inner.end(), [&](int& elem) {

                elem *= myself->m_x;

            });

        });

    }

 

private:

    int m_x;

};

 

int main() {

    Foo f(1000);

 

    vector<vector<int>> v(3, vector<int>(4));

 

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

        for (int j = 0; j < 4; ++j) {

            v[i][j] = i * 10 + j;

        }

    }

 

    f.mult(v);

 

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

        for (int j = 0; j < 4; ++j) {

            cout << v[i][j] << " ";

        }

 

        cout << endl;

    }

}

 

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

meow.cpp

 

C:\Temp>meow

0 1000 2000 3000

10000 11000 12000 13000

20000 21000 22000 23000

 

C:\Temp>g++ -Wall -Wextra -std=c++0x meow.cpp -o meow.exe

 

C:\Temp>meow

0 1000 2000 3000

10000 11000 12000 13000

20000 21000 22000 23000

你可能感兴趣的:(Nested lambda's and 'this' pointers)