我有以下模板类:
template <unsigned N>
class XArray {
static const int Xdata[N];
};
我想为XArray<N>
我使用的每个初始化静态 const 数组,例如 let XArray<N>::Xdata = {1, 2, 3, ..., N}
。怎么做?
我有以下模板类:
template <unsigned N>
class XArray {
static const int Xdata[N];
};
我想为XArray<N>
我使用的每个初始化静态 const 数组,例如 let XArray<N>::Xdata = {1, 2, 3, ..., N}
。怎么做?
你在你的类中声明了一个静态 const int 数组,所以你必须在类声明之外定义静态成员,就像这样:
template<unsigned N>
class XArray
{
public:
static const int array[N];
};
template<unsigned N>
const int XArray<N>::array[N] = {1,2,3,4,5};
但是你必须注意的是:当你使用这个模板时,你必须确保“N”大于你初始化数组的个数;
编辑:
似乎有人已经在其他问题中为您的问题提供了解决方案,并且答案与我的完全一样。
此外,对于更通用的答案,您可以查看此问题的答案。
如果您不介意使用 C++11 功能,那么可变参数模板可能会派上用场:
template <unsigned ...Args>
struct XArrayData
{
static const int Values[sizeof...(Args)];
};
template<unsigned N, unsigned ...Args>
struct _XArrayGenerator
{
typedef typename _XArrayGenerator<N - 1, N, Args...>::Xdata Xdata;
};
template<unsigned ...Args>
struct _XArrayGenerator<1, Args...>
{
typedef typename XArrayData<1, Args...> Xdata;
};
template<unsigned N>
struct XArray
{
typedef typename _XArrayGenerator<N>::Xdata Xdata;
};
template <unsigned ...Args>
const int XArrayData<Args...>::Values[sizeof...(Args)] = { Args... };
解释
XArray
模板结构将数组元素的数量作为模板参数 ( N
)。在编译时,它用于_XArrayGenerator
生成具有N个连续数字的模板参数列表。它以 number 开头N
,然后递归使用自己,直到达到 1。此时,模板参数列表如下所示:
1, 2, ..., N
最后要做的是将这些参数传递给XArrayData
. 代码的最后一行(实际数组的定义)使用参数来初始化数组。
用法
for (int i = 0; i < 3; ++i)
cout << XArray<3>::Xdata::Values[i] << endl;
输出:
1
2
3
您可以如下所示进行初始化。请参阅内联评论以获取我的解释。
template <unsigned N>
class XArray {
private:
static const int Xdata[N];
public:
//I added this for illustration purpose
void print()
{
for (int i = 0; i < N; ++i)
{
std::cout << Xdata[i] << std::endl;
}
}
};
//you can initialize like this
//automatic size counting works with static arrays
//here I initialize with 3 elements
//make sure you don't use N < 3 anywhere
template <unsigned N>
const int XArray<N>::Xdata[] = {1,2,3};
int main(void)
{
XArray<3> obj1; //N = 3: This is okay.
XArray<8> obj2; //N > 3: This is okay. Remaining elements will be 0.
XArray<2> obj3; //N < 3: This is also okay.
obj1.print();
obj2.print();
obj3.print(); //but this will give compilation error
return 0;
}