开发者

Why a template function receives 2D array with 1D reference when a normal function doesn't

void fun (char (&a)[2])  // 1D reference
{}

template<typename T, int SIZE>
void funT (T (&a)[SIZE])  // 1D reference
{}

int main ()
{
  char c[2][2];  // 2D array
  fun(c);  // error
  funT(c); // ok !!!??
}

I can expect that fun() gives error, but how come funT() works fine! Is there any reference in the standard for such behavior or Is it a bug in C++开发者_StackOverflow language?


Because the type of c isn't char [2], it doesn't match the first function. In the template case, T resolves to char [2], which means that the final argument type is char (&a)[2][2]. (You can think of it as the T becoming the equivalent of a typedef to char[2], and expand the argument type based on that.)


T will resolve to char*char[2] and as such there should not be any problems with your templated function.

Edit: Thanks James for pointing that out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜