0
votes

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

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

2
@Andy T: C++0x's unique_ptr isn't an option for me yet, and it would have the same problemChad A
check boost::scoped_ptr or boost::shared_ptrAndriy Tylychko

2 Answers

1
votes

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

1
votes

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