我最近正在阅读一本为 Java 编写的设计模式书籍,但我实际上对将这些技术应用到 C++ 感兴趣,因此我将示例从 Java“翻译”为 C++。我发现在Java中,可以使用lambda表达式作为函数的参数,而不是对象(类的实例)。以我目前的 C++ 知识,我还没有找到一种方法来使用 C++ 做等价或类似的事情,我什至不知道这是否可能,所以我在这里尝试一下。
在 Java 中:
public class Light {
public void on()
{
//whatever
}
public void off()
{
//whatever
}
}
public interface Command {
public virtual void execute();
};
public class RemoteControl {
Command m_command;
public RemoteControl() {}
public void setCommand(Command command)
{
m_command = command;
}
}
根据这本书,在Java中,考虑到接口(interface)的特性(只有一个方法),可以使用带有接口(interface)中声明的方法签名的lambda来代替接口(interface)的“实例”,例如:
RemoteControl remoteControl;
Light livingRoomLight;
remoteControl.setCommand( ()->{livingRoomLight.on();} );
我可以在 C++ 中做什么来实现类似的目标?
我当前的 C++ 代码:
class Light
{
public:
Light() {}
void on()
{
//whatever
}
void off()
{
//whatever
}
};
class Command
{
public:
virtual ~Command() = default;
virtual void execute() = 0;
};
class RemoteControl
{
private:
std::shared_ptr<Command> m_command = {nullptr};
public:
RemoteControl() {}
void setCommand(std::shared_ptr<Command> command)
{
m_command = command;
}
};
在 C++ 中是否可以使用 lambda 表达式而不是指向 Command
实例的指针?
类似于:
std::unique_ptr<RemoteControl> remoteControl = std::make_unique<RemoteControl>();
std::shared_ptr<Light> livingRoomLight = std::make_shared<Light>();
remoteControl->setCommand( [livingRoomLight](){ livingRoomLight->on(); );
或
RemoteControl* remoteControl = new RemoteControl;
Light* livingRoomLight = new Light;
std::function<void()> livingRoomLightOn = [livingRoomLight]() { livingRoomLight->on(); };
remoteControl->setCommand( &livingRoomLightOn );
最佳答案
这是可能的,但你的语法是错误的。以下是如何执行此操作的示例:
#include <iostream>
#include <functional>
class Light
{
public:
void on () { std::cout << "Light on\n"; }
void off () { std::cout << "Light of\n"; }
};
class RemoteControl
{
public:
void setCommand (std::function <void ()> command)
{
m_command = command;
}
void performCommand () { m_command (); }
private:
std::function <void ()> m_command;
};
int main ()
{
Light livingRoomLight;
RemoteControl remoteControl;
remoteControl.setCommand ([&livingRoomLight] () { livingRoomLight.on (); });
remoteControl.performCommand ();
}
输出:
Light on
请注意,livingRoomLight
通过引用传递给 lambda,以便它可以修改原始对象。
关于c++ - 是否可以在 C++ 中使用 lambda 代替类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65382039/