会员功能模板(如你的getData()
)不能是虚拟的。但是,您可以使用虚拟成员函数创建类模板:
template <class T>
class data_ppp {
public:
virtual boost::shared_ptr<T> getData()
{
return boost::shared_ptr<T>(new T());
}
};
这允许进行相当多的自定义。
1)你可以定义一个类data_ppp< std::vector<int> >
。如果该类需要表现为通用T
,那么你就完成了。
2)如果要覆盖特定数据的用途,但所有类型的T
行为,要动态地使用新的功能,你可以从data_ppp<T>
template <class T>
class data_child: public data_ppp<T> {
public:
virtual boost::shared_ptr<T> getData()
{
// add logging, printing or whatever you want
return boost::shared_ptr<T>(new T());
}
};
3)如果派生你只需要重新定义getData()
为T
等于std::vector<int>
,你只需要专门data_ppp
template <>
class data_ppp< std::vector<int> > {
typedef std::vector<int> T;
public:
virtual boost::shared_ptr<T> getData()
{
// add logging, printing or whatever you want
return boost::shared_ptr<T>(new T());
}
};
成员函数模板不能是虚拟的:http://stackoverflow.com/questions/2354210/can-a-member-function-template-be-virtual –
你能用C++ 11编译吗? – 0x499602D2