o7h3rw1s3
o7h3rw1s3

Reputation: 1

Declaring an auto lambda function inside a class

I'm trying to declare a lambda compare function inside a class as such:

class Solve {
private:
    int n, q, first[N+1], depth[N+1], seg[_log(N)+2][(N<<1)+1];
    vector <int> G[N+1], euler;

    auto cmp = [euler, depth] (const int &a, const int &b) -> bool {
        return depth[euler[a]] < depth[euler[b]];
    };
...

But getting the error: error: non-static data member declared with placeholder 'auto'

Declaring the function as static doesn't help: error: capture of non-variable 'Solve::euler' + a bunch of other errors. Explicitly using std::function <> didn't solve it either.

The function is intended for use as in min(a, b, cmp);

Any help is greatly appreciated!

Upvotes: 0

Views: 627

Answers (2)

Onyrew
Onyrew

Reputation: 136

You cannot create a lambda function in the class definition. Move it to the constructor (auto is determined on compile, it's not gonna work here):

class Solve {
    ...
    std::function<bool(int, int)> cmp;
public:
    Solve() :
        cmp{ [&euler = this->euler, &depth = this->depth] (const int& a, const int& b) -> bool {
            return depth[euler[a]] < depth[euler[b]];
        } } {}
};

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96043

There's no need to store the lambda in your class. You can construct one when you need it.

I would create a method for that:

auto MakeComparator() const
{
    return [this](const int &a, const int &b) -> bool
    {
        return depth[euler[a]] < depth[euler[b]];
    };
};

Upvotes: 1

Related Questions