模板类中的数组定义

Array definition in template classes

本文关键字:数组 定义      更新时间:2023-10-16

我已经生成了带有数据数组(一些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;
}