2014-01-20 25 views
1
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() {} 
}; 

在這段代碼中我試過實現一個智能容器。該容器包含指針。它在銷燬時刪除指針。問題在於寫作複製構造函數。它應該複製對象並在容器中放置副本指針。我在這push_back行中收到錯誤,因爲Container::value_type是指針類型,但它需要創建一個解除引用類型的對象。 std::remove_pointer可能在這裏很有用,但我的編譯器不支持C++ 11。也許一個普通的智能指針容器是一個更好的選擇,但我需要解決這個問題。如何實現智能容器的複製構造?

+0

它看起來對我? (到目前爲止)'** iter'你的'Container'類似乎是一個指針類型,所以'push_back'也是正確的。一個用法示例將有助於澄清事物(http://sscce.org) –

+1

@LightnessRacesinOrbit Container :: value_type是T *,那麼'new Container :: value_type'將創建一個'T **'。 – dyp

+0

@dyp:哦,對:) –

回答

3

你可以實現自己的remove_pointer(從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;}; 

然後做typename remove_pointer<Container::value_type>::type

+0

+1我認爲你仍然需要在'Container :: value_type'之前的'typename'。 – dyp

1

更改模板參數。而不是Container使它Container<T*>,那麼你將有基礎對象類型可用。

template <typename Container, typename T> 
class SmartContainer 
    : public Container<T*> 
+0

我不確定你的意思。部分專業化? – dyp

+0

@dyp,對不起,我不是很清楚。我添加了一個例子。 –

+0

在這種情況下,'Container'必須是一個模板模板參數,'template