【发布时间】:2011-11-30 21:37:32
【问题描述】:
我想在我的基类中有一个 typedef 专门用于从这个基类派生的每个类。代码:
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();
}
但这不会编译。有没有办法拥有这个功能?
【问题讨论】:
-
没有模板类型定义。什么具体不起作用?你想做什么,因为总有办法。
-
请包含编译错误
-
@Taz_d 正如其他人所指出的,我们需要进一步澄清。就目前而言,任何人都可以做的就是猜测您的意图并做出一般假设。
标签: c++ oop templates inheritance