【问题标题】:How do I remove code duplication between similar const and non-const member functions in abstract classes?如何删除抽象类中类似 const 和非 const 成员函数之间的代码重复?
【发布时间】:2013-11-03 08:40:32
【问题描述】:

首先,这是对这个问题的后续问题:How do I remove code duplication between similar const and non-const member functions?

假设我有一个抽象类,提供一个纯虚函数:

class ICommand
{
public:
    virtual ~ICommand() {};
    virtual int Execute() = 0;

protected:
    ICommand() {};
};//class ICommand

还有另一个继承自这个的类:

class cCommand : public ICommand
{
public:
    cCommand() {};
    virtual ~cCommand() {};
    virtual int Execute()
    {
        int retval = 0;
        //do something and return appropriate error code

        return retval;
    }
};//class cCommand

现在我需要一个指向 ICommand 类型对象的指针,但需要使用 const 数据,例如:

//using a smart pointer here would be better, but it shows the problem
ICommand const * p = new cCommand();

int retval = p->Execute();  //won't compile

问题是,我在一个 const 对象上调用了一个非 const 成员函数。 所以我要么必须在创建指针 p 时删除 const (不好,我猜......),要么我必须向 ICommand 添加一个 const 成员函数 Execute() 。 在对用户必须实现两个函数而不是(更不用说会发生什么,如果我们在基类中添加一些其他纯虚函数......)这一事实进行了一点挣扎之后,我想出了以下解决方案:

class ICommand
{
public:
    virtual ~ICommand() {};
    virtual int Execute()
    {   //Scott Meyers way
        return static_cast<const ICommand&>(*this).Execute();
    }
    virtual int Execute() const = 0;

protected:
    ICommand() {};
};//class ICommand

这似乎做得很好,但我不确定这是否适合解决我的问题。我认为这对用户来说也不是很直观,因为他总是必须实现纯虚成员函数的 const 版本,而不是非 const 版本。

我的实际问题是,是否有任何我可能没有考虑过的副作用,或者到目前为止我可能已经监督了这个问题是否有更好的解决方案。

提前致谢, 勒内。

【问题讨论】:

    标签: c++ pointers inheritance interface constants


    【解决方案1】:

    是的,如果您希望用户使用const 或非const this 指针调用您提供的方法,那么您必须至少提供@987654324 @ 要调用的函数的版本。请注意,您可以使用非const this 指针调用const 方法。

    考虑Execute 是否需要完全不是const。如果您能够提供Executeconst 版本,那么至少有一个非零概率的Execute 的非const 版本是完全没有必要的。

    所以,直接回答您的问题:

    如何删除类似 const 和 non-const 之间的代码重复 抽象类中的成员函数?

    也许通过完全消除非const 成员函数。

    【讨论】:

    • 总的来说,你是对的。最好的方法是避免使用非const 版本的函数。所以这个例子是为不幸的情况选择的,只有const 函数是不够的。
    猜你喜欢
    • 2010-09-12
    • 2017-06-19
    • 2017-11-22
    • 2020-02-02
    • 2012-01-28
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多