【发布时间】:2016-05-08 18:03:09
【问题描述】:
在Objective C 中,该语言已内置支持将类委托给其他类。 C++ 没有这样的特性(一个类作为另一个类的代表)作为语言的一部分。一种模仿的方法是以这种方式分离声明和实现:
在头文件a.h中:
class AImpl;
class A
{
public:
A();
void f1();
int f2(int a, int b);
// A's other methods...
private:
AImpl *mImpl;
};
在.cpp(实现文件)中:
#include "a.h"
class AImpl
{
public:
AImpl();
// repeating the same method declarations from A
void f1();
int f2(int a, int b);
// AImpl's other methods
};
AImpl::AImpl()
{
}
void AImpl:f1()
{
// actual implemetation
}
int AImpl::f2(int a, int b)
{
// actual implmentation
}
// AImpl's other methods implementation
A::A()
{
mImpl = new AImpl();
}
// A's "forwarder"
void A::f1()
{
mImpl->f1();
}
int A::f2(int a, int b)
{
return mImpl->f2(a, b);
}
// etc.
这需要在类中手动创建所有“转发器”函数,这些函数将委托给另一个类来完成实际工作。乏味,至少可以这么说。
问题是:有没有一种更好的或更高效的方法来使用模板或其他 C++ 语言结构来实现这种效果?
【问题讨论】:
-
您可以在标头中声明一个纯接口,并声明一个工厂函数,而不是所有这些转发。在实现文件中有一个实现接口的类,以及工厂的实现。假设客户端代码不应该能够有意义地扩展类。
-
我不认为有,但我会等待比我更有知识的人来纠正我。
-
我正要写一个关于如何在 C++ 中委托函数的完整列表,但我发现有人已经这样做了:stackoverflow.com/questions/9568150/what-is-a-c-delegate 投票关闭为重复
-
我澄清了这个问题——我对类级委派特别感兴趣,而不是函数级委派。
标签: c++ delegation