gpt4 book ai didi

c++ - 如何使调用代码对被调用的代码一无所知

转载 作者:行者123 更新时间:2023-11-28 08:12:22 25 4
gpt4 key购买 nike

基于 Beyond the C++ Standard Library: An Introduction to Boost ,第 328 页的 Using Boost.Bind with Boost.Function 部分,作者说明了我们可以将调用代码与底层实现代码分离的一种方法。

When separating graphical user interfaces (GUIs) from details on how to handle actions (events) from the user, callbacks of some sort are almost always used. If this callback mechanism is based on function pointers, it is hard to avoid severe limitations of the types that can be used with the callback, which in turn increases the risk of adding coupling between the presentation and the business logic. We can avoid this altogether by using Boost.Function, and when combined with a library that supports argument binding, we can supply the context to invocations of functions with ease. This is one of the most common uses of this libraryto separate knowledge of the business logic from the presentation layer.

class tape_recorder {
public:
void play() {
std::cout << "Since my baby left me...\n";
}

void stop() {
std::cout << "OK, taking a break\n";
}

void forward() {
std::cout << "whizzz\n";
}

void rewind() {
std::cout << "zzzihw\n";
}

void record(const std::string& sound) {
std::cout << "Recorded: " << sound << '\n';
}
};

typedef boost::function<void()> command;

tape_recorder tr;

command play(boost::bind(&tape_recorder::play,&tr));
command stop(boost::bind(&tape_recorder::stop,&tr));
command forward(boost::bind(&tape_recorder::stop,&tr));
command rewind(boost::bind(&tape_recorder::rewind,&tr));
std::string s="What a beautiful morning...";
command record = boost::bind(&tape_recorder::record,&tr,s));


// Invoked from some GUI control...
if (play) {
play.execute();
}

// Invoked from some scripting client...
stop.execute();

With Boost.Function and Boost.Bind, it is possible to achieve the decoupling that makes it possible for the invoking code to know nothing about the code being invoked. It's immensely useful to combine these two libraries in this way.

问题> 我明白上面的代码是如何工作的,但我仍然感到困惑如何将调用代码与真正的实现解耦,就像作者最初想要归档的那样。调用代码(即各种命令)还需要知道tape_recorder的成员函数是什么。那么这里的解耦到底意味着什么?

最佳答案

他所说的只是 Boost 库提供了一种“回调”机制;他给出了一个示例,说明如何使用具有一组通用功能(“打开”、“播放”、“停止”等)的特定类“录音机”。可以想象,您可以编写一个不同的 可能实现相同功能的类(智能手机?)。

这些链接可能有帮助:

http://www.codeproject.com/KB/library/BoostBindFunction.aspx

http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?action=browse&diff=1&id=Boost.Function,_Boost.Bind,_And_Member_Functions

关于c++ - 如何使调用代码对被调用的代码一无所知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8691886/

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