gpt4 book ai didi

c++ - C++ 中的组合模式,是否有首选方法?

转载 作者:行者123 更新时间:2023-11-30 02:10:16 25 4
gpt4 key购买 nike

好吧,让我先说这可能是非常主观和有争议的,可能不属于这里(如果感觉是相互的,请随时关闭)。话虽如此,我正在查看一些代码,我想采用一种标准的组合方法,因为似乎不同的人有不同的风格——所以,这是我到目前为止看到的风格(可能还有更多..) 我关注的特定组合问题是类 B 拥有类 A 的实例,但是,A 需要知道实例,以便它可以调用 B 的方法。

#include <iostream>

using namespace std;

namespace forward
{
class B;

class A
{
public:
A(B& b);
private:
B& inst;
};

class B
{
public:
B() : inst(*this) {}

void foo() { cout << "forward::B::foo()" << endl; }

private:
A inst;
};

A::A(B& b) : inst(b) { inst.foo(); }
}

namespace interface
{
struct IB
{
virtual void foo() = 0;
};

class A
{
public:
A(IB* b) : inst(b) { inst->foo(); }
private:
IB* inst;
};

class B : public IB
{
public:
B() : inst(this) {}

virtual void foo() { cout << "interface::B::foo()" << endl; }

private:
A inst;
};
}

namespace templated
{
template <typename IB>
class A
{
public:
A(IB& b) : inst(b) { inst.foo(); }
private:
IB& inst;
};

class B
{
public:
B() : inst(*this) {}

void foo() { cout << "templated::B::foo()" << endl; }

private:
A<B> inst;
};
}

int main(void)
{
forward::B b1;
interface::B b2;
templated::B b3;

return 0;
}

从这里,我可以看到以下内容(不完整):

前向声明减少需要在 header 中包含 header ,但是您不能使用在该 header 中向前声明的类型 - 即在使用时必须提供完整的类型。

接口(interface)额外的包袱(基类构造、虚函数调用等)

模板化除了编译问题(即荒谬的错误消息等),我看不出有任何问题

现在,我更喜欢模板化方法 - 我认为它很干净并且具有强制编译时间的优点。所以问题的关键是,这种方法在技术上是否存在问题?如果没有,您为什么要采用其他两种方法?


编辑:我认为这个简单的例子没有帮助,在这个特定的例子中,B 是一个资源管理器,并且拥有各种相互关联的组件 (A) - 例如各种网络连接等。所有子组件都可以访问通过 B 彼此 - 整个系统曾经是一堆单例......所以 A 知道 B 的唯一原因是它提供对 A 需要的其他一些组件的访问......

有趣的是,大多数答案都推荐转发,但我仍然不明白为什么这比模板化方法更有优势——除了简单的通用函数之外,是否存在对在代码中使用模板的内在恐惧?

最佳答案

您是否考虑过解决基本设计问题,这样您就没有需要知道其父级才能运行的成员?如果没有关于这种安排的动机的更多信息,很难推荐更好的替代方案,但基本问题似乎是设计问题,而不是技术问题。

编辑听起来您正在寻找 Service Locator .查看它,看看它是否对您的设计问题没有帮助。

关于c++ - C++ 中的组合模式,是否有首选方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4760393/

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