2013-09-16 60 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