Can I define a C++ lambda function without auto?

You use std::function, which can glob any lambda or function pointer.

std::function< bool(int, int) > myFunc = []( int x, int y ){ return x > y; };

See C++ Reference.


You could use std::function, but if that's not going to be efficient enough, you could write a functor object which resembles what lambdas do behind the scenes:

auto compare = [] (int i1, int i2) { return i1*2 > i2; }

is almost the same as

struct Functor {
    bool operator()(int i1, int i2) const { return i1*2 > i2; }
};
Functor compare;

If the functor should capture some variable in the context (e.g. the "this" pointer), you need to add members inside the functor and initialize them in the constructor:

auto foo = [this] (int i) { return this->bar(i); }

is almost the same as

struct Functor {
    Object *that;
    Functor(Object *that) : that(that) {}
    void operator()(int i) const { return that->bar(i); }
};
Functor foo(this);

Tags:

C++

Lambda