'Writing array directly to parameter gives error in c++

#include <iostream>

using namespace std;

template <typename VAR, unsigned int N>
int size(VAR (&arr)[N])
{
return sizeof(arr) / sizeof(arr[0]);
}

int main()
{
cout << size("Test"); //This is working

int x[] = {7, 5, 43, 8};
cout << endl
     << size(x); //And this works too

cout << endl
     << size({7, 9, 7, 9}); //When i try this its give me "no matching function for call to 'size'" error

return 0;
}

Parameter takes strings and arrays that modified outside the parameter. but i need to write the array directly inside the function like the code above. size({some integers});



Solution 1:[1]

Declare the function parameter like

int size( const VAR (&arr)[N])

That is you may not bind a temporary object with a non-constant lvalue reference.

Solution 2:[2]

{1,2,3,4} is not an array, but a list initialization.

Anyhow, don't reinvent the wheel. We already have std::size; for example:

#include <iostream>

int main()
{
    std::cout << std::size("Test") << '\n'; //This is working

    int x[] = {7, 5, 43, 8};
    std::cout << std::size(x) << '\n'; //And this works too

    std::cout << std::size({7, 9, 7, 9}) << '\n'; // this too

    return 0;
}

Solution 3:[3]

Error is because you parameter take address of array(that is rvalue) and you give whole array(that is lvalue ) that's why code give error .

For solve this you make parameter const

`

 #include <iostream>


using namespace std;


 template <typename VAR, unsigned int N>


int size(const VAR (&arr)[N])
   {
 return sizeof(arr) / sizeof(arr[0]);
}

int main()
  {
cout << size("Test"); //This is working

 int x[] = {7, 5, 43, 8};
 cout << endl
 << size(x); //And this works too

 cout << endl
 << size({7, 9, 7, 9}); //When i try this its give me "no matching function for 
 call to 'size'" error

  return 0;
   }`

I hope you get Your answer .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jeff Schaller
Solution 3 Neeraj Jain