C++ 如何为子函数中的函数指定模板参数?
所以我试着:C++ 如何为子函数中的函数指定模板参数?,c++,templates,inheritance,virtual-functions,function-templates,C++,Templates,Inheritance,Virtual Functions,Function Templates,所以我试着: class data_ppp { public: template <class T> virtual boost::shared_ptr<T> getData() { return boost::shared_ptr<T>(new T()); } }; class data_child : public data_ppp { public: template<> ge
class data_ppp {
public:
template <class T>
virtual boost::shared_ptr<T> getData()
{
return boost::shared_ptr<T>(new T());
}
};
class data_child : public data_ppp {
public:
template<>
getData<std::vector<int>>();
};
类数据\u ppp{
公众:
模板
虚拟boost::共享的\u ptr getData()
{
返回boost::shared_ptr(新的T());
}
};
类数据\u子项:公共数据\u ppp{
公众:
模板
getData();
};
但是不能得到想要的效果-我想要一个只返回
boost::shared\u ptr
的类内data\u child getData函数。如何做到这一点?我现在看到的解决您问题的唯一办法是:
class data_ppp
{
public:
template<class T>
std::shared_ptr<T> getData()
{ return std::shared_ptr<T>(new T()); }
};
class data_child : public data_ppp
{
public:
std::shared_ptr<int> getData()
{ return data_ppp::getData<int>(); }
};
类数据\u ppp
{
公众:
模板
std::shared_ptr getData()
{return std::shared_ptr(new T());}
};
类数据\u子项:公共数据\u ppp
{
公众:
std::shared_ptr getData()
{返回数据_ppp::getData();}
};
用法:
data_child dc;
dc.getData();
//dc.getData<float>(); // compilation error
data\u子dc;
dc.getData();
//dc.getData();//编译错误
根据您的描述。您需要具有不同签名的新函数。因此,您将在子类中处理此getdata,因为返回类型不同,因此它的函数非常不同。成员函数模板(如您的getdata()
)不能是虚拟的。但是,您可以使用具有虚拟成员函数的类模板:
template <class T>
class data_ppp {
public:
virtual boost::shared_ptr<T> getData()
{
return boost::shared_ptr<T>(new T());
}
};
3)如果只想将T
的getData()
重新定义为std::vector
,只需专门化data\u 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());
}
};
模板
类数据
typedef std::向量T;
公众:
虚拟boost::共享的_ptrgetData()
{
//添加日志记录、打印或任何您想要的内容
返回boost::shared_ptr(新的T());
}
};
成员函数模板不能是虚拟的:您能用C++11编译吗?
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());
}
};