2
#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});

4
  • 1
    This function already is in the standard library: en.cppreference.com/w/cpp/iterator/size Commented Jan 28, 2022 at 11:57
  • g++ version 11.2.0 (GCC) builds it without error. Commented Jan 28, 2022 at 12:01
  • A non-const lvalue reference can not bind to an rvalue. Here size({7, 9, 7, 9}), the argument {7, 9, 7, 9} is an rvalue. Commented Jan 28, 2022 at 12:08
  • 2
    Unrelated: You could return directly N instead of sizeof(arr) / sizeof(arr[0]) Commented Jan 28, 2022 at 12:23

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

{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;
}

Comments

1

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 .

1 Comment

Welcome to Stack Overflow. Good first answer! But can you clean up the layout a bit?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.