使用模板推导传递数组时变长数组错误 [英] variable length array error when passing array using template deduction
问题描述
您好,在编译以下内容时出现错误。我不确定为什么会这样,如果我将其更改为像[10] [20]这样的const值,它可以工作,但即使声明,似乎也不喜欢该变量,因此它不会更改尺寸。我很困惑为什么这是错误发生,请帮忙。参见下面的代码:
Hi when compiling the following I am getting an error. I am unsure why this is, if I change these to const values like [10][20] it works but doesn't seem to like the variable even though this a declaration so it is not subject to changing the dimensions. I am confused why this is error is occurring please help. See code below:
#include <iostream>
template <size_t X, size_t Y>
void fun (int (&array)[X][Y])
{
std::cout << " do something fun " << std::endl;
}
int main ( int argc, char *argv[] )
{
size_t row (10);
size_t col (20);
int data1[10][20];
fun ( data1 );// compiles
int data2[row][col];
fun ( data2 );// fails
return 0;
}
g++ -I/usr/include -I/usr/local/include -std=c++11 -pthread -O3 -Wall -c main.cpp -o main.o
main.cpp: In function ‘int main(int, char**)’:
main.cpp:18:15: error: no matching function for call to ‘fun(int [(((sizetype)(((ssizetype)row) + -1)) + 1)][(((sizetype)(((ssizetype)col) + -1)) + 1)])’
main.cpp:18:15: note: candidate is:
main.cpp:4:6: note: template<long unsigned int X, long unsigned int Y> void fun(int (&)[X][Y])
main.cpp:4:6: note: template argument deduction/substitution failed:
main.cpp:18:15: note: variable-sized array type ‘int [(((sizetype)(((ssizetype)row) + -1)) + 1)][(((sizetype)(((ssizetype)col) + -1)) + 1)]’ is not a valid template argument
make: *** [main.o] Error 1
推荐答案
int data2 [row] [col];
不是标准的C ++,因为 row
和 col
不是常数表达式。您的编译器有一个扩展,可让您使用具有非恒定尺寸的数组,但这种野兽无法匹配期望具有恒定尺寸的普通阵列的模板签名。
int data2[row][col];
is not standard C++, since row
and col
are not constant expressions. Your compiler has an extension that allows you to use arrays with non-constant dimensions, but such a beast can't match a template signature that expects a normal array with constant dimensions.
鉴于 row
和 col
实际上在您的程序中没有变化,在这种情况下,您可以避免该问题完全声明为 const
,这样 row
和 col
是常量表达式:
Given that row
and col
don't actually vary in your program, in this instance you can avoid the issue altogether by declaring them const
so that row
and col
are constant expressions:
int main ( int argc, char *argv[] )
{
const size_t row (10);
const size_t col (20);
int data1[10][20];
fun ( data1 );// compiles
int data2[row][col];
fun ( data2 );// compiles too!
return 0;
}
这篇关于使用模板推导传递数组时变长数组错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!