开发者

C++ Template specialization on a non-concrete type (another template class!)

I'm porting some code to use smart pointers in some places, and I ran into an issue with specialization. Specializing a template function on a concrete type is very straightforward, but what if I want to specialize a specific method on another templatized class (in my case, std::auto_ptr)? I can't seem to find the right magic words to make my compiler not cry.

Here's a code sample:

#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){}
    iSomeInte开发者_开发问答rface* 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;
}

I'm trying to override the tSomeContainer::getInterfacePtr() method when the type is a std::auto_ptr, but I just can't make it go


You cannot partially specialize a single member of a class template. (You can partially specialize the whole class template, with identical definitions except for that one member, but that's usually not fun.)

Instead, you can use overloaded function templates:

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


does

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

work for you?

I seem to remember running into issue with the above if it is also defined for non-template classes. YMMV

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜