c++ - 方法链接与多态性 C++

标签 c++ polymorphism fluent

是否可以编写返回派生类型的流畅的链宁方法?考虑以下两个类:

class Base {
protected:
    std::string mFoo;
public:
    Base& withFoo(std::string foo) {
        mFoo = foo;
        return *this;
    }
};

class Derived : public Base {
protected:
    std::string mBar;
public:
    Derived& withBar(std::string bar) {
        mBar = bar;
        return *this;
    }

    void doOutput() {
        std::cout << "Foo is " <<
            mFoo << ".  Bar is " <<
            mBar << "." << std::endl;
    }
};

然后我想构建我的对象并像这样使用它:

Derived d;
d.withFoo("foo").withBar("bar").doOutput();

这当然会失败,因为 withFoo 返回一个 Base。由于我所有的 with 方法都只是设置成员变量,所以我可以先指定派生的 with。问题是我的构建器方法(上例中的 doOutput)需要单独的语句。

Derived d;
d.withBar("this is a bar")
    .withFoo("this is my foo");
d.doOutput();

我的问题是 withFoo 是否有某种方法可以返回未知的派生类型,以便 Base 可以与多个派生类无缝地使用(毕竟,*this 一个Derived,虽然Base(正确地)不知道这个事实。

对于更具体的示例,我正在编写一些类来访问 REST 服务器。我有一个 RestConnection 类,方法是 withUrl,一个 PostableRest 类,方法是 withParamdoPost 和一个带有 doGetGettableRest 类。我怀疑这是不可能的,并且可能会尝试将一堆虚拟方法塞进 RestConnection 但我讨厌在有多个 withParam 重载时这样做,其中一些不包含在 GET 参数列表中是有意义的。

提前致谢!

最佳答案

我想你可以利用 CRTP在这里,类似于下面的内容,其中派生类告诉基类它是什么类型:

class Base
{
    // Abstract/virtual interface here.
};

template <class Derived>
class Base_T : public Base
{
private:
    std::string mFoo;

public:
    Derived& withFoo(std::string foo) {
        mFoo = foo;
        return *static_cast<Derived*>(this);
    }
};

class Derived : public Base_T<Derived> {
private:
    std::string mBar;
public:
    Derived& withBar(std::string bar) {
        mBar = bar;
        return *this;
    }

    void doOutput() {
        std::cout << "Foo is " <<
            mFoo << ".  Bar is " <<
            mBar << "." << std::endl;
    }
};

关于c++ - 方法链接与多态性 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384701/

相关文章:

nhibernate - 实体没有持久化

c++ - 为什么指向未定义结构的指针有时在 C 和 C++ 中是非法的

c++ - OpenGL 新纹理在删除后替换旧纹理

java - 多态性:方法改变,但参数值不变

c++ - 使用子函数的继承函数

c++ - 有没有更好的方法来处理为层次结构中的类分配身份以供运行时使用?

c++ - 在 C++ 中使用引用进行向上转换

c++ - 如何在 Qt/C++ 中有效地重新初始化多维数组?

java - 简化的 Java 单行验证、赋值和返回

php - 如何使用 Laravel 4.2 批量删除数据库表中不在数组中的行