C++ 设计用于在C+中的容器中同时使用所有子类+;
我刚刚读了一篇关于奇怪的重复模板模式的文章。您可以使用它模拟带有模板的虚拟函数 例如:C++ 设计用于在C+中的容器中同时使用所有子类+;,c++,templates,C++,Templates,我刚刚读了一篇关于奇怪的重复模板模式的文章。您可以使用它模拟带有模板的虚拟函数 例如: template<class T> struct A { void func() { static_cast<T*>(this)->func(); } }; struct B : public A<B> { void func() { cout << "B" << endl; } };` 模板 结构A { void func
template<class T>
struct A
{
void func() { static_cast<T*>(this)->func(); }
};
struct B : public A<B>
{
void func() { cout << "B" << endl; }
};`
模板
结构A
{
void func(){static_cast(this)->func();}
};
结构B:公共A
{
void func(){cout为模板类定义非模板抽象基类。使用基类处理容器。您可以执行以下操作:
class NonTemplateBase
{
};
template<class T>
struct A : public NonTemplateBase
{
void func() { static_cast<T*>(this)->func(); }
};
类非模板库
{
};
模板
结构A:公共非模板库
{
void func(){static_cast(this)->func();}
};
然后创建指向非模板库的指针向量(即std::vector
)
但是,我猜您希望能够对向量中的对象调用func()
或其他成员函数,并且希望这些调用以多态方式调用派生类中正确的成员函数
这是行不通的,因为奇怪的重复模板模式只允许您执行静态(即编译时)多态性。如果您想要运行时多态性,您必须使用虚拟函数。让所有模板实现一个公共接口,并创建指向该接口的指针或引用向量
class Icommon //interface
{
public:
virtual void print() = 0;
};
template <class T>
class MyCommon : public Icommon
{
T obj;
public:
MyCommon(T o):obj(o) {}
void print() {cout << obj;}
};
main()
{
MyCommon<int> i(1);
MyCommon<char> c('t');
vector<Icommon *> commonVec;
commonVec.push_back(&i);
commonVec.push_back(&c);
}
类Icommon//接口
{
公众:
虚空打印()=0;
};
模板
MyCommon类:公共Icommon
{
T-obj;
公众:
霉氨(TO):obj(o){}
无效打印(){cout