0

いくつかの場所でスマートポインターを使用するためにいくつかのコードを移植していますが、特殊化の問題が発生しました。テンプレート関数を具象型に特化するのは非常に簡単ですが、特定のメソッドを別のテンプレート化されたクラス(私の場合はstd :: auto_ptr)に特化したい場合はどうすればよいですか?コンパイラを泣かせないための適切な魔法の言葉を見つけることができないようです。

コードサンプルは次のとおりです。

#include <memory> // std::auto_ptr
#include <iostream> // std::cout
class iSomeInterface
{
public:
    virtual void DoSomething() = 0;
};

class tSomeImpl : public iSomeInterface
{
public:
    virtual void DoSomething() { std::cout << "Hello from tSomeImpl"; }
};

template <typename T>
class tSomeContainer
{
public:
    tSomeContainer(T& t) : _ptr(t){}
    iSomeInterface* getInterfacePtr();
private:
    T _ptr;
    // usage guidelines
    tSomeContainer();
};

template <typename T>
iSomeInterface* tSomeContainer<T>::getInterfacePtr()
{
    return _ptr;
}

void testRegularPointer()
{
    tSomeImpl* x = new tSomeImpl();
    tSomeContainer<tSomeImpl*> xx(x);
    xx.getInterfacePtr()->DoSomething();
    delete x;
}
#if 1
// specialize for auto_ptr
template <typename T>
iSomeInterface* tSomeContainer< std::auto_ptr<T> >::getInterfacePtr()
{
    return _ptr.get();
}

void testAutoPtr()
{
    std::auto_ptr<tSomeImpl> y(new tSomeImpl);
    tSomeContainer< std::auto_ptr<tSomeImpl> > yy(y);
    yy.getInterfacePtr()->DoSomething();
}
#else
void testAutoPtr()
{
}
#endif

int main()
{
    testRegularPointer();
    testAutoPtr();
    return 0;
}

タイプがstd::auto_ptrの場合、tSomeContainer :: getInterfacePtr()メソッドをオーバーライドしようとしていますが、うまくいきません。

4

2 に答える 2

1

します

template <template<typename> class PtrCtr, typename Ptr>
class tSomeContainer<PtrCtr<Ptr> >
{...};

あなたのために働きますか?

テンプレート以外のクラスにも定義されている場合、上記の問題に遭遇したことを覚えているようです。YMMV

于 2011-03-09T22:29:47.063 に答える
1

クラステンプレートの単一のメンバーを部分的に特殊化することはできません。(クラステンプレート全体を部分的に特殊化することができ、その1つのメンバーを除いて同じ定義を使用できますが、通常は面白くありません。)

代わりに、オーバーロードされた関数テンプレートを使用できます。

namespace ntSomeContainerImpl {
    template <typename T>
    T* getInterfacePtr(T* ptr) { return ptr; }
    template <typename T>
    T* getInterfacePtr(const std::auto_ptr<T>& ptr) { return ptr.get(); }
}

template <typename T>
iSomeInterface* tSomeContainer<T>::getInterfacePtr()
{ return ntSomeContainerImpl::getInterfacePtr( _ptr ); }
于 2011-03-09T22:46:58.730 に答える