Is it possible to use a lambda expression as a class attribute? I'm working on a little game in C++ where all bots have the same update routine, but everyone should have his own optional extra update routine.
I thought something like that
class Bot
{
private:
Lambdatype lambda;
public:
Bot(Lambda l) {lambda = l;}
update() { dosomething(); lambda(); }
};
By the way, you cannot always use lambda expression in place of Anonymous class, because of its limitation of being SAM type. If you are using an anonymous class to implement an interface with two abstract methods then you cannot replace it with a lambda of Java 8.
The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition.
A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.
Finally, an abstract class can't refer to a lambda expression, while the interface can have a single abstract method that can refer to a lambda expression.
You can use std::function
, for example assume it's void
function and gets two int
:
class Bot
{
private:
using Lambda = std::function<void(int, int) >;
Lambda lambda;
public:
Bot(const Lambda &l) : lambda(l)
{
}
void update()
{
//dosomething...;
lambda(1, 2);
}
};
int main()
{
Bot bot ([](int x, int y){ cout << x+y << endl; });
bot.update();
}
More generic:
template <typename L>
class Bot
{
private:
L lambda;
public:
Bot(const L &l) : lambda(l)
{
}
void update()
{
//dosomething...;
lambda(1, 2);
}
};
int main()
{
Bot<std::function<void(int,int)>> bot (
[](int x, int y){ cout << x+y << endl; }
);
bot.update();
}
Template based:
template <typename L>
struct Bot
{
private:
L lambda;
public:
Bot(const L &l) : lambda{l} {}
void update() { lambda(1,2); }
};
int main()
{
auto l = [](int x, int y){ std::cout << x + y << std::endl; };
Bot<decltype(l)> bot(l);
bot.update();
}
Addional you may use make_bot
template< class L >
struct bot
{
bot( L l ) : lambda{l} {}
void update() { lambda(1,2); }
private:
L lambda;
};
template< class L > bot<L> make_bot(L l ) { return {l}; }
int main()
{
auto my_bot = make_bot( [](int x, int y){ std::cout << x + y << std::endl;} ) ;
my_bot.update();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With