开发者

templated typedefs and inheritance

开发者 https://www.devze.com 2023-04-10 21:39 出处:网络
I want to have a typedef in my base class to be specialized to each class derived from this base class. code:

I want to have a typedef in my base class to be specialized to each class derived from this base class. code:

template<class X>
class SharedPointer
{
public:
    X* data;
    SharedPtr(X *val)
    {
        data = val;
    }
};

template<class T=Base> /* default type, I know this is a mistake. 
The reason to have this here is to just indicate that the default argument 
should be Base itself. so it'll have a Base type of shared pointer. */
class Base
{
public:
    typedef SharedPointer<T> MyTypeOfPtr;
    virtual MyTypeOfPtr Func()
    {
        Base *b = new Base;
        return MyTypeOfPtr(b);
    }
};

class Derived : Base<Derived>
开发者_开发问答{
public:
    MyTypeOfPtr Func()
    {
        Derived *d = new Derived;
        return MyTypeOfPtr(d);      
    }
};

main()
{
 Base b;
 Base::MyTypeOfPtr ptr1 = b.Func();
 Derived d;
 Derived::MyTypeOfPtr ptr2 = d.Func();  
}

but this doesn't compile. is there a way to have this functionality?


You have to get all sorts of details right:

  • Spelling: "SharedPointer" or "SharedPtr"?

  • Templates and classes aren't the same thing, so you can't have class T = Base: T is a class, Base isn't. Also, you can't have the default refer to itself, so even class T = Base<T> doesn't work. Remove the default type.

  • Class inheritance is private by default, so say class Derived : public Base<Derived>.

  • Make the constructor of SharedPointer public.

  • Base::Func() makes no sense; maybe it should say new T.

I should seriously suggest that you start with simpler examples and build up slowly.

0

精彩评论

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

关注公众号