1

所以我尝试:如何在子项中指定函数的模板参数?

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>>(); 
}; 

,但不能获得预期的效果 - 我想在课堂data_child的getData函数将只返回boost::shared_ptr<std::vector<int>>。如何做这样的事情?

+0

成员函数模板不能是虚拟的:http://stackoverflow.com/questions/2354210/can-a-member-function-template-be-virtual –

+0

你能用C++ 11编译吗? – 0x499602D2

回答

1

您的问题,唯一的解决办法,我现在看到的是:

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>(); } 
}; 

用法:

data_child dc; 
dc.getData(); 
//dc.getData<float>(); // compilation error 
1

根据你的描述。您需要具有不同签名的新功能。因此,您将在子类中处理此getdata,就好像它的非常不同的函数一样,因为返回类型是不同的。

0

会员功能模板(如你的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()); 
    } 
}; 
相关问题