gpt4 book ai didi

c++ - C++中按钮的简单信号

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:07 25 4
gpt4 key购买 nike

我一直在研究一些信号/槽实现,它们无一异常(exception)地非常复杂,有些甚至依赖于 MOC 和额外的代码生成,例如 Qt。

我意识到存在威胁安全等问题,但对于简单的单线程场景,采用简单方法是否有问题,例如:

typedef void (*fPtr)();

class GenericButton
{
public:
GenericButton() : funcitonToCall(nullptr) {}
void setTarget(fPtr target) {
funcitonToCall = target;
}

void pressButton() {
if (funcitonToCall) funcitonToCall();
}

private:
fPtr funcitonToCall;
};

void doSomething(){
std::cout << "doing something..." << std::endl;
}

void doSomethingElse(){
std::cout << "doing something else..." << std::endl;
}

int main(){
GenericButton myButton;
myButton.setTarget(doSomething);
myButton.pressButton();
myButton.setTarget(doSomethingElse);
myButton.pressButton();
}

仍然可以链接其他几个方法并在目标 void 函数中传递数据。那么为什么在单击按钮时执行某些代码这样微不足道的事情会如此复杂。

最佳答案

这是一个非常明智的解决方案,但不要将自己局限于函数指针。使用 std::function,它允许您绑定(bind)事物、调用对象的成员函数、使用 lambda 并仍然在有意义的地方求助于函数指针。示例:

#include <iostream>
#include <functional>

using namespace std::placeholders;


class GenericButton
{
public:
typedef std::function<void()> fPtr;
GenericButton() : funcitonToCall(nullptr) {}
void setTarget(fPtr target) {
funcitonToCall = target;
}

void pressButton() {
if (funcitonToCall) funcitonToCall();
}

private:
fPtr funcitonToCall;
};

struct foo {
void doSomething() const {
std::cout << "doing something in a foo..." << std::endl;
}

static void alternative(int i) {
std::cout << "And another, i=" << i << "\n";
}
};

void doSomethingElse() {
std::cout << "doing something else..." << std::endl;
}

int main() {
GenericButton myButton;
foo f;
myButton.setTarget(std::bind(&foo::doSomething, &f));
myButton.pressButton();
myButton.setTarget(doSomethingElse);
myButton.pressButton();
myButton.setTarget(std::bind(foo::alternative, 666));
myButton.pressButton();
myButton.setTarget([](){ std::cout << "Lambda!\n"; });
myButton.pressButton();
}

C++ 中几乎总是有比函数指针更好的解决方案。

如果您没有std::function/std::bind,在 boost 中总有替代方案可以工作,您可以推出自己的 std: :function 没有太多工作的替代方案,如果你想做这样的事情,这是值得做的。

大多数信号/槽机制都可以追溯到 boost::bind 之类的东西不可行的时代。那些日子早已一去不复返了,你可以获得比函数指针更复杂的标准和更灵活的东西。

关于c++ - C++中按钮的简单信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com