PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] Why C++ template array length deduction need to be like "f(T (&a)[N]"?

 July 04, 2022     arrays, c++, pass-by-reference, pass-by-value, templates     No comments   

Issue

Use C++ template to know the length of C-style array, we need this:

#include<stdio.h>
template<class T,size_t N>
size_t length(T (&a)[N]){ return N; }
int main() {
    int fd[2];
    printf("%lld\n", length(fd));;
    return 0;
}

It works, prints 2. My question is about the syntax.

In the declaration of length, why the parameter should be like (&a)[N], and a[N] doesn't work?

If I change to

template<class T,size_t N>
size_t length(T a[N]){ return N; }

gcc will say:

template argument deduction/substitution failed:
couldn't deduce template parameter 'N'

Why need an extra & and a pair of braces around array identifier here, what's the template rule / syntax rule behind this?

Appreciate detailed explanations.


Solution

In this function declaration

template<class T,size_t N>
size_t length(T a[N]){ return N; }

the compiler adjusts the parameter having the array type to pointer to the array element type.

That is this declaration actually is equivalent to

template<class T,size_t N>
size_t length(T *a){ return N; }

On the other hand, the array used as an argument expression in this call

length(fd)

is implicitly converted to a pointer to its first element.

So the compiler cannot deduce the value of the template non-type parameter N.

When the parameter is declared as a reference then such an adjustment and implicit conversion as described above do not occur. The reference serves as an alias for the array.

Pay attention to that to output objects of the unsigned integer type size_t with the C function printf you need to use the conversion specifier zu instead of lld.



Answered By - Vlad from Moscow
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing