模板类中的数组定义
Array definition in template classes
我已经生成了带有数据数组(一些const静态,有些可突变(和访问者方法的配置文件。问题在于,现在的一种数据类型将要模板,但是我根本无法让编译器接受它。
模板类型是一种非POD,但默认的构造。
使用BO的定义在CPP文件中,但是由于我不知道代码生成代码时的模板类型,所以我不能再做。
即。我想要以下内容(如果可以的话,甚至可以在标题之外的定义(
template<typename T>
class LargeConfig :
{
public:
// methods
private:
static const POD1 POD_ONES[];
T ManyTs[];
};
template<typename T>
static const POD1 LargeConfig<T>::POD_ONES[] =
{
{ 0U, 1U}, // instance 1
{ 1U, 1U}, // instance 2
...
};
template<typename T>
T LargeConfig<T>::ManyTs[] =
{
T(), // instance 1
T(), // instance 2
...
};
目前,我可以在此处获得" "存储类, pod_ones 定义和" " 不可定义非静态数据成员在其类之外定义"对于 Manyts 。
,但肯定必须有某种方法来在C 中的类中创建模板的非平凡数组?到目前为止,我只找到了模板类型是整数类型的示例。
首先,ManyTs
未声明static
,因此关于nonstatic data member defined outside of class
的错误。
然后,当您定义static
成员时,请勿将关键字static
放置:
template<typename T>
class LargeConfig
{
public:
// methods
private:
static const POD1 POD_ONES[];
static T ManyTs[];
};
template<typename T>
const POD1 LargeConfig<T>::POD_ONES[] =
{
{ 0U, 1U}, // instance 1
{ 1U, 1U}, // instance 2
};
template<typename T>
T LargeConfig<T>::ManyTs[] =
{
T(), // instance 1
T() // instance 2
};
我编译了示例演示(将您的static
数据成员公开以快速访问它们(
您自己指示,您有两个问题,让我从第二个问题开始。
ManyTs
定义为LargeConfig的常规成员,这意味着应在您的班级构造函数中初始化它。一个例子:
template<typename T>
LargeConfig<T>::LargeConfig()
: ManyTs
{ T(), // instance 1
T(), // instance 2
...
}
{}
我很难猜测,因为我设法通过以下定义了pod1
对其进行编译。struct POD1
{
POD1(unsigned, unsigned);
unsigned _1{};
unsigned _2{};
};
我怀疑您要么不包括班级,要么是其他班级出现的问题,但是,我们看不到,这很难说。
试图在此处编译您的代码(G 5.4(我在第7行中遇到了语法错误。纠正我们得到的:
templates.cpp:16:44: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive]
static const POD1 LargeConfig<T>::POD_ONES[] =
^
templates.cpp:23:26: error: ‘T LargeConfig<T>::ManyTs []’ is not a static data member of ‘class LargeConfig<T>’
T LargeConfig<T>::ManyTs[] =
^
templates.cpp:23:26: error: template definition of non-template ‘T LargeConfig<T>::ManyTs []’
第一个消息与此问题有关。您不能使用静态来定义数据类型,仅用于声明。
通过简单使ManyTs
成员静态来纠正最后一个错误。
然后,代码变成这样的东西:
class POD1 {
};
template<typename T>
class LargeConfig
{
public:
// methods
private:
static const POD1 POD_ONES[];
static T ManyTs[];
T ManyTsAgain[10];
};
template<typename T>
const POD1 LargeConfig<T>::POD_ONES[] =
{
{ 0U, 1U}, // instance 1
{ 1U, 1U}, // instance 2
};
template<typename T>
T LargeConfig<T>::ManyTs[] =
{
T(), // instance 1
T(), // instance 2
};
int main() {
LargeConfig<int> obj1;
LargeConfig<POD1> obj2;
return 0;
}
相关文章:
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- C++编程从外部文本文件定义数组大小
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 删除动态数组时未定义标识符
- 在定义字符数组(井字游戏)的 for 循环中应用输入限制
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 模板类中的数组定义
- C 结构数组定义
- 在C++中为指针数组定义NULL
- 为什么局部变量不隐藏数组定义中的全局变量
- 静态数组定义错误 C++
- C++ 二维数组定义
- 这是否是 C++ 中的有效 2D 数组定义
- 模板类数组定义不是类型名称、静态或枚举器C++
- 用静态2d数组定义类的方便方法是什么(并且2d数组的大小只有在编译时才知道)
- 如何将字符数组定义为常量
- 二维数组定义
- 如何保护数组定义,防止使用非零值进行不完整的初始化
- 为3D数组定义setter/getter属性
- 在静态成员数组定义中对自身使用sizeof操作符