2013-09-16 214 views
2

關於一些不編譯的代碼的一個非常快速的問題。 我寫周圍的std ::載體的包裝:矢量初始化矢量

template <class T> 
class CLArray 
{ 
public: 
    /// Constructor, destructor. 
    CLArray(const size_t size); 
    CLArray(const size_t size, const T value); 
    ~CLArray(); 

    /// Copy constructor and copy assignment operator. 
    CLArray(const CLArray& rhs); 
    CLArray& operator=(const CLArray& rhs); 

    /// Move constructor and move assignment operator. 
    CLArray(CLArray&& rhs); 
    CLArray& operator=(CLArray&& rhs); 

    void swap(CLArray& other) 
    { 
     std::swap(data_, other.data_); 
    } 

    typedef typename std::vector<T>::iterator iterator; 
    typedef typename std::vector<T>::const_iterator const_iterator; 

    iterator begin() 
    { 
     return data_.begin(); 
    } 

    const_iterator begin() const 
    { 
     return data_.begin(); 
    } 

    iterator end() 
    { 
     return data_.end(); 
    } 

    const_iterator end() const 
    { 
     return data_.end(); 
    } 

    T& operator[](const size_t index) throw(CLException); 
    T operator[](const size_t index) const throw(CLException); 

    T At(const size_t index) const throw(CLException); 
    void SetAt(const size_t index, const T& value) throw(CLException); 

    void Insert(ubyte* data, const size_t size); 

    size_t GetSize() const; 

    const CLArray<T>& GetData() const; 

    void Clear(); 

private: 
    std::vector<T> data_; 
}; 

,我想創建一個類來管理一個2維CLArray:

template <class T> 
class SomeMap 
{ 
public: 
    SomeMap(const size_t width, const size_t heigth, const T defaultVal = 0) 
     : map_(width, CLArray<T>(heigth, defaultVal)) 
    { 
     // Allocate enough memory for all objects 
    } 

    ~SomeMap() {} 

private: 
    CLArray<CLArray<T>> map_; 
    //std::vector<std::vector<T>> map_; 
}; 

我得到一個錯誤:聲明一個對象時no matching function for call to ‘CLArray<Cell*>::CLArray()SomeMap<Cell*> map(748, 480, nullptr);我真的不明白爲什麼... `

回答

1

CLArray沒有默認的構造函數,向量的幾種方法需要噸至是缺省構造

當你實例是:

SomeMap<Cell*> map(748, 480, nullptr); 

SomeMap有一個私有成員:

CLArray<CLArray<T>> map_; 

CLArray在私人會員的情況下,存儲vector<T>,T是CLArray。這個成員的SomeMap的成員評估爲vector<CLArray<Case*>>vector要求包含的對象是默認可構造的。 CLArray沒有默認的構造函數。因此,你會得到一個編譯器錯誤,它可能在向量代碼的深處試圖實例化一個T.

您可能會期望CLArray應該有一個默認的構造函數。然而,當你指定任何構造函數時,你將失去C++默認給你的默認構造函數。 (見here)。

+1

std :: vector是否真的需要其模板參數是默認可構造的?它真的取決於你所調用的成員函數/構造函數。 – mfontanini

+0

它的工作原理,感謝有用的答案,這是一個虛擬的問題! – Athanase

+0

@mfontanini你是對的。你可以避免使用默認的構造函數,但是它使得使用vector的某些方法相當笨拙,因爲你必須傳入一個實例 –

1

您的類CLArray<>缺少默認的構造函數。這是type參數std::vector<type>所需的參數,並在其默認構造函數中使用。在你的情況下type=CLArray<Cell*>

順便說一句,從來沒有一個好主意,不包括任何功能包裝工作代碼。

+0

嗨,謝謝你的回答。我需要一個包裝器,因爲我想限制矢量的使用(例如禁止使用push_back),但是我想使用可行的東西(std :: vector相當強壯:))。 – Athanase

+0

它的工作原理,感謝有用的答案,這是一個虛擬的問題! – Athanase