我正在尝试使用静态多态性和模板来创建一个可以容纳更多一种类型的容器,根据我对模板的了解,它无法完成,但我希望我错了,并且有一个方法。我有以下课程:
template<class Derived>
class base
{
public:
base(string);
void clean()
{
cout << "I'm cleannig \n";
}
void process()
{
static_cast<Derived*>(this)->setup();
static_cast<Derived*>(this)->run();
static_cast<Derived*>(this)->cleanup();
}
string name;
};
template<class Derived>
base<Derived>::base(string y):name(y)
{
}
class derived : public base<derived>
{
friend class base<derived>;
void setup() {cout << "derived setup \n"; }
void run() { cout << "derived run \n"; }
void cleanup() { cout << "derived cleanup \n"; }
};
class derived1 : public base<derived1>
{
friend class base<derived1>;
void setup() {cout << "derived1 setup \n"; }
void run() { cout << "derived1 run \n"; }
void cleanup() { cout << "derived1 cleanup \n"; }
};
我不会创建一个可以容纳它们的容器,我尝试了这段代码 -
template <class T>
class Y{
public:
std::vector<base<T>> m_vec;
};
template <typename T>
class D:public Y<T>
{
public:
friend class Y<T>;
void print()
{
for(auto& e: Y<T>::m_vec)
{
e.process();
}
}
};
int main()
{
base<derived>* b = new base<derived>;
base<derived1>* c = new base<derived1>;
D<derived> y;
y.m_vec.push_back(b);
y.m_vec.push_back(c);
y.print();
}
但它不起作用我试图这样做:
y.m_vec.push_back(static_cast<base<derived>>(c));
我收到了这个错误:
错误:没有匹配函数调用 'std::vector, std::allocator > >::push_back(base*&)' y.m_vec.push_back(b);