我正在尝试替换模板上的虚拟功能:
struct Derived1;
struct Derived2;
template <typename T>
struct Base
{
void f();
};
template<>
void Base::f<Derived1>(){std::cout<<"Derived1\n";}
template<>
void Base::f<Derived2>(){std::cout<<"Derived2\n";}
struct Derived1 : public Base {};
struct Derived2 : public Base {};
它一直有效,直到我们创建一个指针容器:
std::vector<Base*> vec;//doesn't work - needs explicit parameter for Base
vec.push_back(new Derived1);
vec[0]->f();//Call f() from Derived1
在这种情况下是否可以摆脱“虚拟性”?