重载函数而不重写它们的整个定义

Overloading functions without rewriting their whole definition

参见以下示例:

class bar{
    private:
        unsigned _timeout;
    public:
        bool foo(unsigned arg);
        bool foo(unsigned arg, unsigned timeout);
};

bool bar::foo(unsigned arg){
    /*50 lines of code*/
    if (_timeout > 4)
       //...
}

bool bar::foo(unsigned arg, unsigned timeout){
    /*50 lines of code*/
    if (timeout > 4)
       //...
}

如您所见,这些函数仅在一行中有所不同 - 第一个函数使用私有成员 _timeout,第二个函数检查作为参数传递的变量超时。这里的问题是,我必须重写整个 ~50 行代码才能重载此函数。有什么解决方法吗?

这个怎么样:

bool bar::foo(unsigned arg)
{
    return foo(arg, _timeout);
}

两种选择:要么将通用功能提取到它自己的函数中(重构),要么调用另一个。

在您的情况下,您可以这样定义第一个重载:

bool bar::foo(unsigned arg) {
    return foo(arg, _timeout);
}

总的来说,重构也是一个不错的方法:

void bar::foo_inner(unsigned arg) { // or however it should be declared
    // 50 lines of code
}

bool bar::foo(unsigned arg) {
    foo_inner(arg);
    if (_timeout < 4)
        ...
}

bool bar::foo(unsigned arg, unsigned timeout) {
    foo_inner(arg);
    if (timeout < 4)
        ...
}

根据另外两个私有函数实现这两个函数:

class bar{
    private:
        unsigned _timeout;

        void fooImplBegin(unsigned arg);
        bool fooImplEnd(unsigned arg);
    public:
        bool foo(unsigned arg);
        bool foo(unsigned arg, unsigned timeout);
};

void bar::fooImplBegin(unsigned arg) {
    /*50 lines of code */
}

bool bar::fooImplEnd(unsigned arg) {
    /* more lines of code, returning something */
}

bool bar::foo(unsigned arg){
    fooImplBegin(arg);
    if (_timeout > 4)
       //...
    return fooImplEnd(arg);
}

bool bar::foo(unsigned arg, unsigned timeout){
    fooImplBegin(arg);
    if (timeout > 4)
       //...
    return fooImplEnd(arg);
}