簡體   English   中英

c ++:使用模板在類中定義可變長度數組

[英]c++: defining variable-length array within a class using templates

我正在嘗試構建一個MapV2類。 在類中,我想將一個Cell對象數組作為私有成員(Cell是另一個類)。 我試圖得到它,以便地圖的大小由構造函數使用的模板參數分配。 即,我試圖得到類似於以下內容:

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文件)的代碼中要做什么來使其工作。 我覺得這些錯誤很容易解決。 任何幫助深表感謝。

請參閱為什么模板只能在頭文件中實現? 欲獲得更多信息。 如果您嘗試使用顯式實例化來緩解問題,那么您的模板參數是非類型的,因此它們必須如下所示:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM