模板类中的C++静态常量数组初始化
C++ static const array initialization in template class
我有以下模板类:
template <unsigned N>
class XArray {
static const int Xdata[N];
};
我想为我使用的每个XArray<N>
初始化静态常量数组,例如,让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个连续数字的模板参数表。它从数字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;
}
相关文章:
- 私有类型的静态常量成员
- 分离一个静态常量 std::thread?
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 我可以在运行时重新定义在 OpenCascade/OCCT 标头中定义的 c++ 静态常量吗?
- 如何为静态常量模板化专用整数值分配存储
- 使用什么代替"静态常量 TCHAR *"
- C++ 模板中的静态常量初始化顺序
- 如何在编译时解析静态常量 std::string?
- 关于静态常量数据模因的声明和定义的混淆
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 为什么在第二类中使用静态常量会在第一类中给出编译器错误?
- 静态常量与常量局部变量,哪一个性能更好
- 如何在模板类中设置静态常量变量
- public:静态常量字符串声明/初始化问题
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 对静态常量积分类型的未定义引用
- 全局变量中的静态常量与常量
- c++ 类中的静态常量变量和常量变量在存储方面是否有区别
- 避免在静态常量类上定义但不使用
- 指向静态常量对象的共享指针?