use*_*735 6 c++ arrays templates
我正在尝试构建一个MapV2类.在类中,我想将一个Cell对象数组作为私有成员(Cell是另一个类).我试图得到它,以便地图的大小由构造函数使用的模板参数分配.即,我试图得到类似于以下内容:
const size_t arraySize = 12;
MapV2<arraySize> myMapV2;
Run Code Online (Sandbox Code Playgroud)
这是我的文件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];
};
Run Code Online (Sandbox Code Playgroud)
这是Map.cpp:
#include <iostream>
#include "MapV2.h"
MapV2<size_t M, size_t N>::MapV2()
{
}
MapV2::~MapV2()
{
}
Run Code Online (Sandbox Code Playgroud)
这是主要功能:
int main()
{
const size_t xLength = 6;
const size_t yLength = 8;
MapV2 <xLength, yLength> Example;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试编译时,我得到以下一堆错误:
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
Run Code Online (Sandbox Code Playgroud)
我已经用Google搜索了这个问题并且花了一些时间尝试遵循类似StackOverflow帖子中给出的建议,但是没有一个示例告诉我们在实际构造函数(即MapV2.cpp文件)的代码中要做什么来使其工作.我觉得这些错误很容易解决.任何帮助深表感谢.
小智 2
请参阅为什么模板只能在头文件中实现?了解更多信息。如果您尝试使用显式实例化来缓解问题,则您的模板参数是非类型的,因此它们必须如下所示:
\n\ntemplate class MapV2<6, 8>; //et. all for all possible number combinations\n
Run Code Online (Sandbox Code Playgroud)\n\n如果你尝试这样做:
\n\ntemplate class MapV2<size_t, size_t>;\n// or this, replace unsigned long int with what size_t is on your system\ntemplate class MapV2<unsigned long int, unsigned long int>;\n
Run Code Online (Sandbox Code Playgroud)\n\n你会得到这个令人难以置信的错误:
\n\nerror: expected a constant of type \xe2\x80\x98long unsigned int\xe2\x80\x99, got \xe2\x80\x98long unsigned int\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n\n那是因为它需要一个 long unsigned int 而不是type。
\n\n您可以看到为什么这会成为一个问题。我会将构造函数的定义移至标头中以避免出现麻烦。
\n\nstruct Cell {};\n\ntemplate<size_t M, size_t N>\nclass MapV2\n{\n\npublic:\n // Declaration\n MapV2();\n ~MapV2();\nprivate:\n Cell myMapV2[M*N];\n};\n\n// Definition\ntemplate<size_t M, size_t N>\nMapV2<M, N>::MapV2()\n{\n\n}\n\ntemplate<size_t M, size_t N>\nMapV2<M, N>::~MapV2()\n{\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
950 次 |
最近记录: |