gpt4 book ai didi

c++ - Mixin和接口(interface)实现

转载 作者:太空狗 更新时间:2023-10-29 20:56:10 25 4
gpt4 key购买 nike

根据 http://www.thinkbottomup.com.au/site/blog/C%20%20_Mixins_-_Reuse_through_inheritance_is_good

But hang on a minute, none of this helps us plug into our Task Manager framework as the classes do not implement the ITask interface. This is where one final Mixin helps - a Mixin which introduces the ITask interface into the inheritance hierarchy, acting as an adapter between some type T and the ITask interface:

template< class T >
class TaskAdapter : public ITask, public T
{
public:
virtual void Execute()
{
T::Execute();
}

virtual std::string GetName()
{
return T::GetName();
}
};

Using the TaskAdapter is simple - it's just another link in the chain of mixins.

// typedef for our final class, inlcuding the TaskAdapter<> mixin
typedef public TaskAdapter<
LoggingTask<
TimingTask<
MyTask > > > task;

// instance of our task - note that we are not forced into any heap allocations!
task t;

// implicit conversion to ITask* thanks to the TaskAdapter<>
ITask* it = &t;
it->Execute();

ITaskMyTask 实现时,为什么需要 TaskAdapter?另外如果ITask不是抽象的,可能会导致菱形问题。

最佳答案

那是一篇非常很酷很有趣的文章。

在最后一个 Mixin 示例中,MyTask不是派生自 ITask。这意味着它不能转换为在最后完成的 ITask 指针。

在该示例中,我相信您可以从 ITask 派生 MyTask。但我认为作者想说明您甚至可以使用 TaskAdapter 解耦 MyTask 类。

关于c++ - Mixin和接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193264/

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