简体   繁体   English

如何将模板类存储在向量中?

[英]How to store template class in a vector?

I've following code and i want to store Base<A> * a,Base<B> * b in a vector without losing typename,so i want to achieve vector<.....> vec; vec.push_back(a); vec.push_back(b); 我遵循以下代码,我想将Base<A> * a,Base<B> * b在向量中而不丢失类型名,因此我想实现vector<.....> vec; vec.push_back(a); vec.push_back(b); vector<.....> vec; vec.push_back(a); vec.push_back(b); and call like this vec[0]->DoJob(3,4); vector[1]->DoJob(3,4,"blablba"); 并像这样调用vec[0]->DoJob(3,4); vector[1]->DoJob(3,4,"blablba"); vec[0]->DoJob(3,4); vector[1]->DoJob(3,4,"blablba"); . How can i do it? 我该怎么做? I can change design completely if there is a way to accomplish this. 如果有办法,我可以完全更改设计。

/*this code works*/
template<typename T>
class Base{
protected:
    virtual ~Base(){}
public:
    template<typename ... Args>
    void DoJob(Args ... args){
        T * t = dynamic_cast<T*>(this);
        t->print(args...);
    }
};


class A:public Base<A>{
public:
    void print(int a, int b){
        cout << a << b << endl;
    }
};

class B :public Base<B>{
public:
    void print(float a, double b, string s){
        cout << a << b << s << endl;
    }
};


Base<A> * a = new A();
a->DoJob(3, 4);
Base<B> * b = new B();
b->DoJob(3, 4,"blabla");

One fairly common way to implement something like that would be to have a container with a pointer to a common superclass. 一种类似的实现方法是使用一个容器,该容器带有指向公共超类的指针。

class BaseSuperclass {
// ...
};

template<typename T> class Base : public BaseSuperclass {
// ...
};

std::vector<BaseSuperclass *> vector;

Then any Base<T> * can be pushed into your vector. 然后可以将任何Base<T> *推入向量中。

Note that when you iterate over, or retrieve the contents of your vector, all you'll end up getting back is a BaseSuperclass * . 请注意,当您遍历或检索向量的内容时,最终得到的只是BaseSuperclass * You'll then have to figure out which subclass you have at hand. 然后,您必须确定手头有哪个子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM