Question

So I try:

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

but cant get desired effect - I want to have in class data_child getData function that would only return boost::shared_ptr<std::vector<int>>. How to do such thing?

Was it helpful?

Solution

The only solution to your problem that I see now is:

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

Usage:

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

OTHER TIPS

According to your description. You want new function with different signature. Thus you will treat this getdata in the child class as if its very different function since the return type is different.

Member function templates (like your getData()) cannot be virtual. However, you can have a class template with virtual member functions:

template <class T>
class data_ppp {
public:        
    virtual boost::shared_ptr<T> getData()
    {
        return boost::shared_ptr<T>(new T());
    }
};

THis allows quite a lot of customization.

1) you can define a class data_ppp< std::vector<int> >. If that class needs to behave as a generic T, then you are done.

2) If you want to override behavior for specific data uses but for all types T and you want to use the new functionality dynamically, you can derive from 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) If you only want to redefine getData() for T equal to std::vector<int>, you only have to specialize 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());
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top