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

Saturday, June 25, 2022

[FIXED] Why does the "size_of_array" template fucntion does not work with int a[n] (size defined at runtime) while it works fine with int a[4]?

 June 25, 2022     c++, compiler-errors, templates, variable-length-array     No comments   

Issue

template <typename T, int n >
int tell_me_size(T (&) [n]){
  return n;
}

this code works fine with

int a[4];
cout<< tell_me_size(a)<<endl;

while does not work with

int n;
cin>>n;
int a[n];
cout<< tell_me_size(a)<<endl;

The later gives the error "no matching function for call to ‘tell_me_size(int [n])"


Solution

According to the C++ 20 Standard (13.4.3 Template non-type arguments)

2 A template-argument for a non-type template-parameter shall be a converted constant expression (7.7) of the type of the template-parameter.

Pay attention to that variable length arrays like this

int n;
cin>>n;
int a[n];

are not a standard C++ feature.



Answered By - Vlad from Moscow
Answer Checked By - Cary Denson (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