开发者

C++ subclass parameterized class, and use the subclass as a specialization

I want something like this:

class TestParent<class T>
{
    T* some();
}

class TestChild : public TestParent<TestChild>
{};

Is t开发者_StackOverflow社区his possible?

Thanks.


Absolutely! This technique is often used in advanced techniques like the Curiously Recurring Template Pattern or to implement static polymorphism. You'll see it a lot if you do advanced C++ programming.


This is possible but only if you define an implementation of some otherwise you'll be confronted by compilation errors. You may also want to add a protected constructor so that your base class can't be created and used outside of how you define it in your header scope.

template<typename T>
class TestParent{
    public:

        T* some() { return new T(); }

    //this is suggested
    protected:
        TestParent(){}
};

class TestChild : public TestParent<TestChild>{}

This is used in the curiously recuring template pattern and other techniques from policy-based design made popular by Alexandrescu's book.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜