Objective-C的类别构造或技术在C + +? [英] Objective-C's category-like construct or technique in C++?
问题描述
Objective-C类别功能允许程序员添加未在原始类定义中定义的新方法。
Objective-C category feature allows programmer to add new method which was not defined in original class definition.
我可以在C ++上存档类似的功能(语言构造或某种技术)吗?
Can I archive similar functionality (language construct or some technique) on C++?
调用语法(。
或 - >
运算符)。
Major concern is consistent method calling syntax (.
or ->
operator).
推荐答案
让我们考虑扩展下面的类:
Let's consider the following class to be extended:
struct A {
int x, y;
A(int x, int y) : x(x), y(y) {}
};
您可以继承此类或编写包含此类的实例的包装类。在大多数情况下,继承是要走的路,因为包装器类不是 A,而是包装(包含)A。
You can inherit from this class or write a wrapper class which contains an instance of this class. In most cases, inheritance is the way to go, as a wrapper class isn't an A but it wraps (contains) an A.
使用C ++ 11移动语义,将一个实例 A
推广到子类 B
(继承 A
)将是高效的,并且不需要复制实例 A
:
With C++11 move semantics, promoting an instance A
to a subclass B
(inheriting A
) will be efficient and doesn't require to copy the instance A
:
class B : public A {
public:
B (A &&a) : A(a), someOtherMember(a.x + a.y) {}
// added public stuff:
int someOtherFunction() const { return someOtherMember; }
private:
// added private stuff:
int someOtherMember;
};
完整代码示例: http://ideone.com/mZLLEu
当然,我添加的功能有点蠢(成员甚至更多,因为它不尊重原始成员 x
和 y
的进一步更改,但您应该了解
Of course the function I added is a bit silly (and the member even more, since it doesn't respect further changes of the original members x
and y
), but you should get an idea of what I want to demonstrate.
请注意构造函数 B(A& a)
调用促销构造函数(这不是一个标准术语)。通常, B(B& b)
是一个移动构造函数,其移动 B
实例转换为要构建的新 B
。我使用移动语义将 A
(由另一个函数返回)的实例移动到超级-class A
of B
。
Note the constructor B (A &&a)
which is something I call "promote constructor" (this is not a standard term). Normally, B (B &&b)
is a move constructor, which moves the contents of the provided B
instance into a new B
about to be constructed. I use the move semantics to move an instance of A
(which has been returned by another function) into the super-class A
of B
.
可以促进 A 到
B
,同时可以使用 B
作为 A
。
Effectively, you can promote A
to B
while making it possible to use a B
as an A
.
与Soonts的回答相反,我的解决方案也适用于添加的虚拟表,因为它不依赖于不安全的指针转换。
In contrast to Soonts' answer, my solution also works with added virtual tables, since it doesn't rely on unsafe pointer casting.
这篇关于Objective-C的类别构造或技术在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!