c++:使用模板在类中定义可变长度数组

标签 c++ arrays templates

我正在尝试构建一个类 MapV2。在类中,我希望有一个 Cell 对象数组作为私有(private)成员(Cell 是另一个类)。我正在尝试获取它,以便 map 的大小由与构造函数一起使用的模板参数分配。即,我正在尝试获得类似于以下内容的内容:

const size_t arraySize = 12;
MapV2<arraySize> myMapV2;

这是我的文件 Map.h:

#pragma once
#include <iostream>
#include "Cell.h"

template<size_t M, size_t N>
class MapV2
{

public:
    MapV2();
    ~MapV2();
private:
    Cell myMapV2[M*N];
};

这是 Map.cpp:

#include <iostream>
#include "MapV2.h"

MapV2<size_t M, size_t N>::MapV2()
{

}

MapV2::~MapV2()
{

}

这里是主要功能:

int main()
{
    const size_t xLength = 6;
    const size_t yLength = 8;
    MapV2 <xLength, yLength> Example;
    return 0;
}

但是当我尝试编译时,出现了以下乱七八糟的错误:


Compiling: MapV2.cpp
D:\Users\Vik\ModSim1a\MapV2.cpp:4: error: wrong number of template arguments (1, should be 2)

D:\Users\Vik\ModSim1a\MapV2.h:7: error: provided for 'template<unsigned int M, unsigned int N> class MapV2'

D:\Users\Vik\ModSim1a\MapV2.cpp: In function 'int MapV2()':
D:\Users\Vik\ModSim1a\MapV2.cpp:4: error: 'int MapV2()' redeclared as different kind of symbol

D:\Users\Vik\ModSim1a\MapV2.h:7: error: previous declaration of 'template<unsigned int M, unsigned int N> class MapV2'

D:\Users\Vik\ModSim1a\MapV2.cpp:7: warning: no return statement in function returning non-void

D:\Users\Vik\ModSim1a\MapV2.cpp: At global scope:
D:\Users\Vik\ModSim1a\MapV2.cpp:9: error: expected constructor, destructor, or type conversion before '::' token

Process terminated with status 1 (0 minutes, 0 seconds)
5 errors, 1 warnings

我用 Google 搜索了这个问题,并花了一些时间尝试遵循类似 StackOverflow 帖子中给出的建议,但是没有一个示例说明在实际构造函数(即 MapV2.cpp 文件)的代码中要做什么才能得到这个工作。我觉得这些错误有一个简单的修复方法。非常感谢任何帮助。

最佳答案

参见 Why can templates only be implemented in the header file?想要查询更多的信息。如果您尝试使用显式实例化来缓解该问题,您的模板参数是非类型的,因此它们必须如下所示:

template class MapV2<6, 8>; //et. all for all possible number combinations

如果您尝试这样做:

template class MapV2<size_t, size_t>;
// or this, replace unsigned long int with what size_t is on your system
template class MapV2<unsigned long int, unsigned long int>;

你会得到这个令人难以置信的错误:

error:   expected a constant of type ‘long unsigned int’, got ‘long unsigned int’

那是因为它需要一个 long unsigned int 而不是类型

您会明白为什么这会成为一个问题。我会将构造函数的定义移到标题中以避免麻烦。

struct Cell {};

template<size_t M, size_t N>
class MapV2
{

public:
    // Declaration
    MapV2();
    ~MapV2();
private:
    Cell myMapV2[M*N];
};

// Definition
template<size_t M, size_t N>
MapV2<M, N>::MapV2()
{

}

template<size_t M, size_t N>
MapV2<M, N>::~MapV2()
{

}

关于c++:使用模板在类中定义可变长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21472191/

相关文章:

c++ - 用户创建程序失败

c++ - 树莓派 I2C

objective-c - 在iOS编程中保存/检索数组的最佳方法是什么

php - 在选中复选框的位置插入数组

c++ - C/C++ 中的宏扩展

c++ - 如何查看指针映射中的指针是否不为 0

java - 使用字符串数组在 Java 中创建二维( map )数组

templates - VS2010 Professional 中的 Windows Phone 模板

c++ - 模板标签的困惑

templates - 为什么 Rust 不能使用泛型参数的大小作为数组长度?