Pregunta

struct Delete
{
     template <typename T>
     void operator() (T* t)
     {
         delete t;
     }
};

template <typename Container>
class SmartContainer
     : public Container
{
public:
     ~SmartContainer()
     {
         std::for_each(Container::begin(), Container::end(), Delete());
     }

     SmartContainer(const SmartContainer& other)
     {
         for (typename Container::const_iterator iter = other.begin(); iter != other.end(); ++iter) {
             push_back(new typename Container::value_type(**iter));
         }
     }

   SmartContainer() {}
};

In this code I have tried implement a smart container. The container contains pointers. It deletes the pointers when it is destroyed. The problem is in writing copy constructor. It should copy the object and put pointers of copies in the container. I am getting error in this push_back line because Container::value_type is pointer type but it needs to create an object of dereferenced type. std::remove_pointer may be useful here but my compiler doesn't support c++11. Maybe a normal container with smart pointers is a better choice but I need solution for this.

¿Fue útil?

Solución

You could implement your own remove_pointer (from cppreference.com):

template< class T > struct remove_pointer                    {typedef T type;};
template< class T > struct remove_pointer<T*>                {typedef T type;};
template< class T > struct remove_pointer<T* const>          {typedef T type;};
template< class T > struct remove_pointer<T* volatile>       {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};

Then do typename remove_pointer<Container::value_type>::type.

Otros consejos

Change the template parameter. Instead of Container make it Container<T*>, then you'll have the base object type available.

template <typename Container, typename T>
class SmartContainer
     : public Container<T*>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top