给定类的布局(Base-> Derived; Base-> Derived2),以及我将实例作为基类指针(Base* baseder2 = new Derived2
)保留到派生类的事实,我希望能够使用实例化TemplClass实例。派生类型(类似于sh = new TemplClass<Derived2>(baseder2)
)。下面的代码实例化
sh = new TemplClass<Base>(baseder2)
,由于未在类function
中声明fn Base
,导致编译错误。如何找出baseder2
指针的派生类型,最好是没有dynamic_cast?现实生活中的代码有许多Base后代,因此我想避免使用带有dynamic_cast的if语句。我一直在研究boost::type_traits,但老实说,不要做什么。
模板函数template <typename T> BaseTemplClass* foo(T* t)
只是工厂obj的la脚借口。
最好的祝福,
多多尔
class Base
{
public:
virtual ~Base(){}
};
class Derived : public Base
{
public:
virtual ~Derived(){}
void function()
{
std::cout<<"This is Derived"<<std::endl;
}
};
class Derived2 : public Base
{
public:
virtual ~Derived2(){}
void function()
{
std::cout<<"This is Derived2"<<std::endl;
}
};
class BaseTemplClass
{
public:
virtual void Print() =0;
};
template <class Tmodel>
class TemplClass : public BaseTemplClass
{
public:
TemplClass(Tmodel* m)
{
model = m;
}
void Print()
{
model->function();
std::cout << " TemplClass"<<typeid(model).name() << std::endl;
}
Tmodel *model;
};
template <typename T> BaseTemplClass* foo(T* t)
{
BaseTemplClass* sh;
std::cout << "FOO: "<<typeid(t).name() << std::endl;
sh = new TemplClass<T>(t);
return sh;
}
int main(int argc, char **argv)
{
Derived* der = new Derived;
Derived2* der2 = new Derived2;
Base* baseder2 = new Derived2;
BaseTemplClass* sh = foo(der);
sh->Print();
delete sh;
sh = foo(der2);
sh->Print();
delete sh;
sh = foo(baseder2);
sh->Print();
delete sh;
delete der;
delete der2;
delete baseder2;
return 0;
}
最佳答案
在您的情况下真的需要模板类吗?在给定的示例中,您可以将方法“function”添加到基类,并将其虚拟化。
但是,如果仍然需要模板类,则可以执行以下操作:
class Base
{
public:
virtual ~Base(){}
virtual BaseTemplClass* createTemplClass() = 0;
};
class Derived : public Base
{
public:
virtual ~Derived(){}
void function()
{
std::cout<<"This is Derived"<<std::endl;
}
virtual BaseTemplClass* createTemplClass()
{
return new TemplClass<Derived>( this );
}
};
class Derived2 : public Base
{
public:
virtual ~Derived2(){}
void function()
{
std::cout<<"This is Derived2"<<std::endl;
}
virtual BaseTemplClass* createTemplClass()
{
return new TemplClass<Derived2>( this );
}
};
template <typename T> BaseTemplClass* foo(Base* t)
{
BaseTemplClass* sh;
std::cout << "FOO: "<<typeid(t).name() << std::endl;
sh = t->createTemplClass();
return sh;
}