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>>です。そのようなことをする方法は?

4

3 に答える 3

1

あなたの説明によると。別の署名を持つ新しい関数が必要です。したがって、戻り値の型が異なるため、この getdata を子クラスで非常に異なる機能であるかのように扱います。

于 2013-01-21T17:40:34.650 に答える
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
于 2013-01-21T16:51:03.143 に答える
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) equal toのみを再定義getData()したい場合は、特殊化するだけで済みますTstd::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());
    }
};
于 2013-01-21T19:55:34.067 に答える