C ++: defining an array of variable length inside a class using templates

I am trying to build a MapV2 class. In the class, I would like to have an array of Cell objects as a private member (Cell is another class). I am trying to get it so that the size of the map is set by the template parameter used with the constructor. Ie, I'm trying to get something like the following:

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

Here is my Map.h file:

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

template<size_t M, size_t N>
class MapV2
{

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

Here is Map.cpp:

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

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

}

MapV2::~MapV2()
{

}

And here is the main function:

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

But when I try to compile, I get the following mess of errors:


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

Googled, , , StackOverflow, , ( MapV2.cpp), . , . .

+4
1

. ? . , , , :

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’

, 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()
{

}
+1

Source: https://habr.com/ru/post/1524635/


All Articles