[英]const array of fixed size const array as argument of a method in C++
在我關於將數組作為const參數傳遞的問題之后,我試圖找出如何編寫一個參數為固定大小的const數組的const數組的方法。 唯一可寫的是這些數組的內容。
我在想這樣的事情:
template <size_t N>
void myMethod(int* const (&inTab)[N])
{
inTab = 0; // this won't compile
inTab[0] = 0; // this won't compile
inTab[0][0] = 0; // this will compile
}
此解決方案中的唯一問題是我們不知道第一個維度。 有人對此有解決方案嗎?
提前致謝,
凱文
[編輯]
我不想使用std :: vector或此類動態分配的數組。
如果兩個維度在編譯時都是已知的,則可以使用二維數組(換句話說,數組的數組),而不是使用指向數組的指針的數組:
template <size_t N, size_t M>
void myMethod(int (&inTab)[N][M])
{
inTab = 0; // this won't compile
inTab[0] = 0; // this won't compile
inTab[0][0] = 0; // this will compile
}
int stuff[3][42];
myMethod(stuff); // infers N=3, M=42
如果在運行時不知道任何一個維度,則可能需要動態分配數組。 在這種情況下,請考慮使用std::vector
來管理分配的內存並跟蹤大小。
該引用阻止第4行( inTab = 0;
),因為您已將inTab
用作引用。 const阻止第5行( inTab[0] = 0;
),因為inTab
指針是const。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.