自动调用C ++基类方法 [英] Call a C++ base class method automatically

查看:188
本文介绍了自动调用C ++基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实施命令设计模式,但我绊倒了一个概念问题。让我们假设你有一个基类和几个子类,如下面的例子:

I'm trying to implement the command design pattern, but I'm stumbling accross a conceptual problem. Let's say you have a base class and a few subclasses like in the example below:

class Command : public boost::noncopyable {
    virtual ResultType operator()()=0;

    //Restores the model state as it was before command's execution.
    virtual void undo()=0;

    //Registers this command on the command stack.
    void register();
};


class SomeCommand : public Command {
    virtual ResultType operator()(); // Implementation doesn't really matter here
    virtual void undo(); // Same
};

事情是每次操作符()在SomeCommand实例上调用,我想通过调用Command的register方法将* this添加到堆栈(主要用于undo目的)。我想避免从SomeCommand :: operator()()调用register,但是要把它叫做automaticaly(someay ;-))

The thing is, everytime operator () is called on a SomeCommand instance, I'd like to add *this to a stack (mostly for undo purposes) by calling the Command's register method. I'd like to avoid calling "register" from SomeCommand::operator()(), but to have it called automaticaly (someway ;-) )

当你构造一个子类,如SomeCommand,基类构造函数称为automaticaly,所以我可以添加一个调用注册。我不想调用register的事情,直到调用operator()()。

I know that when you construct a sub class such as SomeCommand, the base class constructor is called automaticaly, so I could add a call to "register" there. The thing I don't want to call register until operator()() is called.

我该怎么办?我想我的设计有点缺陷,但我真的不知道如何使这项工作。

How can I do this? I guess my design is somewhat flawed, but I don't really know how to make this work.

推荐答案

它看起来像您可以从NVI(非虚拟接口)习惯中受益。 命令对象的接口没有虚拟方法,但会调用到私有扩展点:

It looks as if you can benefit from the NVI (Non-Virtual Interface) idiom. There the interface of the command object would have no virtual methods, but would call into private extension points:

class command {
public:
   void operator()() {
      do_command();
      add_to_undo_stack(this);
   }
   void undo();
private:
   virtual void do_command();
   virtual void do_undo();
};

这种方法有不同的优点,首先是您可以在基础中添加通用功能类。其他优点是您的类的接口和扩展点的接口不会彼此绑定,因此您可以在公共接口和虚拟扩展接口中提供不同的签名。搜索NVI,你会得到更多和更好的解释。

There are different advantages to this approach, first of which is that you can add common functionality in the base class. Other advantages are that the interface of your class and the interface of the extension points is not bound to each other, so you could offer different signatures in your public interface and the virtual extension interface. Search for NVI and you will get much more and better explanations.

附录:原始 article by Herb Sutter,他介绍了概念(未命名)

Addendum: The original article by Herb Sutter where he introduces the concept (yet unnamed)

这篇关于自动调用C ++基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆