Template class constructor issues - designing a container for multidim arrays
I'm trying to create my own container for an array of any dimension for numerical computing. I would like to do this using templates so that I could overload the subscript operator [] so that it works like normal arrays and vectors e.g. access entries like a[10][10][10] etc.
I am having trouble getting the constructor to work when trying to create containers to hold multidimensional arrays. Please help!
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
using namespace std;
template <class T>
class container{
public:
inline T& operator[](int i){return data[i];}
container(int si, T initval){
size=si;
data=new T[size];
transform(dat开发者_StackOverflow社区a,data+size,data, [initval] (T d) {return initval;});
// transform fills array with the initial value.
}
~container(){delete [] data;}
private:
T* data;
int size;
};
int main(){
//For example:
vector<vector<int>> v1(10,vector<int>(10,0)); //2D 10x10
vector<vector<vector<int>>> v2(10,vector<vector<int>>(10,vector<int>(10,0)));
//3D 10x10x10
container<int> c1(10,0); //1D 10x1 works!
container<container<int>> c2(10,container<int>(10,0)); //2D 10x10 fails!
system("pause");
return 0;
}
VS10 error output:
error C2512: 'container<T>' : no appropriate default constructor available
with
[
T=int
]
c:\users\jack\documents\visual studio 2010\projects\ref\ref\ref.cpp(11) : while compiling class template member function 'container<T>::container(int,T)'
with
[
T=container<int>
]
c:\users\jack\documents\visual studio 2010\projects\ref\ref\ref.cpp(28) : see reference to class template instantiation 'container<T>' being compiled
with
[
T=container<int>
]
Build FAILED.
I know I could just use valarray or a boost library, but I would like to understand how to create my own. Efficiency is important. Thanks!
Your constructor uses the expression new T[size]
and this requires T
to be default constructible (if T
is a class type).
You need to do something like: allocate raw memory (e.g. using operator new
) and construct T
instances "in place" using a placement new
expression. Alternatively, you could just give container
a default constructor.
You are missing a lot of constructors. You need a default constructor and a copy constructor at the very least, operator=
too.
- Give container a default constructor, that takes no parameters. It looks like you want to make your container non-resizable though.
- You could make the dimension of container a template parameter and ignore the T initVal
- If you do that you probably don't even need to use new[] and delete[] but if you do you need the full "rule of 3" of copying and assigning to be properly implemented.
- You might find a const overload of operator[] useful too.
see this
or review boost::multi_array<>
What you are trying to do: requires advance template programming skills, therefore reviewing boost will be a good start IMHO.
精彩评论