开发者

Child class as return type for a class method

I have a C++ class which is meant to be inherited. All its children will inherit a method:

class Record {
pu开发者_如何转开发blic:
    RETTYPE* all();
};

class Child : public Record {
    int age;
    char *name;
};

int main() {
    Child boo;
    Child boos* = boo->all(); // Pointer to array of Children
    return 0;
};

How can I make a method return (a pointer to) itself? I can't just say Record all(); as Child is not Record. The method will never be called on Record. Always on some class inherited from Record.


Here's one way

class Record {

};

template<class T>
class RecordOf : public Record {
public:
    T* all();
};

class Child : public RecordOf<Child> {
    int age;
    char *name;
};

Each subclass now has an all method that returns the exact type. You can put methods that are virtual and have the same signature in subclasses in Record and ones that depend on exact type in RecordOf.

It's called the Curiously Recurring Template pattern

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜