class myclass{
//definitions here
};
myclass e;
int myarray[10];
/*
Do something...
*/
e = myarray;
In order to make e = myarray
possible, I overloaded the = operator. And I have to get the length of the incoming array length.
template <class T>
int getarrlen(T& arr)
{
return sizeof(arr) / sizeof(arr[0]);
}
myclass::operator=(int obj[]) {
int len=getarrlen(obj);
//Do something...
}
But the return value of getarrlen(obj)
is always 1.
So, how can I get the length of obj[] in the overloading function?
By the way, I've also tried int size = *(&arr + 1) - arr;
and it didn't work either.
Update0: For this:
template<typename T1, int size>
int getarrlen(T1(&)[size]) { return size; }
I got a C2784 compiler-error in Visual Studio... Strange... Update1: The code provided by the link from @AlgirdasPreidžius works for the main function, but it doesn't work for my code:( Also, to make it more obvious, I've tried this:
#include<iostream>
using namespace std;
int x[10];
//Begin of the copied code
template <std::size_t N>
struct type_of_size
{
typedef char type[N];
};
template <typename T, std::size_t Size>
typename type_of_size<Size>::type& sizeof_array_helper(T(&)[Size]);
#define sizeof_array(pArray) sizeof(sizeof_array_helper(pArray))
//End
void myv(int a[]) {
const std::size_t n = sizeof_array(a); // constant-expression!
cout << n << endl;
}
int main() {
int a[20] = {1,2,3,4,5};
myv(a);
}
The code doesn't work. And I've tried to add template <typename T, std::size_t Size>
above void myv(int a[]) {
and it didn't work work either...