问题描述
我想为数值计算的任何维度的数组创建自己的容器。我想使用模板,这样我可以重载下标运算符[],使其工作原理类似于正常的数组和向量。访问条目像[10] [10] [10]等。
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(data,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 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.
我知道我可以使用valarray或boost库,但我想了解如何创建我自己的。效率很重要。感谢!
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!
推荐答案
您的构造函数使用表达式 new T [size]
并且这需要 T
是默认可构造的(如果 T
是类类型)。
Your constructor uses the expression new T[size]
and this requires T
to be default constructible (if T
is a class type).
你需要做一些事情:分配原始内存(例如使用 operator new
)并构造 T
使用展示位置 new
表达式in place。或者,您可以给 container
一个默认构造函数。
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.
这篇关于模板类构造函数问题 - 设计多字节数组的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!