The exprssion is seen in the code snippet below.
For convenience, the question is clearly stated in the comment.
#include <functional>
#include <iostream>
#include <deque>
#include <string>
class Light
{
public:
Light(std::string name):m_name(name){}
void on()
{
std::cout << m_name << "'s light has been turned on just now" << std::endl;
}
void off()
{
std::cout << m_name << "'s light has been turned off just now" << std::endl;
}
void dim()
{
std::cout << m_name << "'s light has been dimmed just now" << std::endl;
}
void brighten()
{
std::cout << m_name << "'s light has been brightened up just now" << std::endl;
}
private:
std::string m_name;
};
class LightInvoker
{
public:
void add_cmd(std::function<void()> cmd) {
m_to_run.push_back(std::move(cmd));
}
void execute_all_cmd() {
for (auto& cmd: m_to_run)
cmd();
}
private:
std::deque<std::function<void()>> m_to_run;
};
int main()
{
auto bedroom_light = Light("bedroom");
LightInvoker invoker;
invoker.add_cmd([&]{ bedroom_light.on(); }); //never saw such expression, but it works indeed.
//why there is a ';' in the {} and there is [&] other than &. I can understand std::bind(&Light::on, bedroom_light);
invoker.add_cmd(std::bind(&Light::on, bedroom_light)); //I can understand this.
invoker.add_cmd([&]{ bedroom_light.dim(); });
invoker.add_cmd([&]{ bedroom_light.dim(); });
invoker.execute_all_cmd();
}