Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

crazy template to get the lenght of an array

Status
Not open for further replies.

whitespider

Programmer
Mar 10, 2009
7
BR
I'm a brasilian. So please excuse me any mistakes.
Does anybody knows how this templates works? I got this example in the web, and voila it works properly. But I have no idea how. I am new in C++ ( I used to program in Delphi) but my new job requires a deep knowledge in C++.
Can you help me please?!
The templates supposedly gets the size of an array (not in bytes) but in number of elements.

template <typename T, int N>
char (&len(T(&)[N]))[N];

thanks anyway
 
I doubt the code is portable.

What does the len() function look like?
Do you have the link to the page where you found this code?
 
I doubt the code is portable.

What does the len() function look like?
Do you have the link to the page where you found this code?

cpjust I really don't remember. What u see up there (the template) is the declaration of the len function. There is no other code for the len. But it works. If you wanna try it do this:
declare the len function exactly like that and then call it like this: sizeof len(array);
Don't ask me why I have to call the sizeof function before.
Thank u for ansering.
 
cpjust,
by the way I'm having a very hard time to create a similar template. The problem seems to be the way C++ deals with arrays. As far as I can understand the C++ never uses the real array as a parameter for a function. In fact the parameter is always a pointer to the first element of the array, and that situation causes a lot of trouble when I try to do something like this, inside a function or procedure:
sizeof(array)/sizeof(array[0])
This function shuold get the number of elements in the array. Instead it returns the number of bytes allocated in the heap. I would like to create a function similiar to the delphi's lenght().
Try this. Create yourself a template exactly like this:
template <typename T>
int Array_Size(T *Array)
{
return(sizeof(array)/sizeof(array[0]);
}
You'll see that the template will return 1. Because the array is only the pointer to the first position and not the hole thing.
Now try it directly. I mean :

int tam;
tam = sizeof(array)/sizeof(array[0]); it works! How is it possible!
 
I can't tell how it works just by looking at it, but I'll probably give the len() template a try when I get home.

In C/C++, arrays always degrade to a pointer to their first element when you pass them to a function. Therefore, when passing an array to a function, you also have to pass the size of the array as another parameter.

In C++ you should really be using std::vector<T> instead of plain old arrays. Vectors can grow automatically and have a size() function and many other useful member functions.

Here are some Tutorials you might want to look at:
 
I tried compiling this code on gcc:
Code:
#include <iostream>

using namespace std;

template <typename T, int N>
char (&len(T(&)[N]))[N];

int main()
{
        const char str[] = "Hello World!";
        cout << str << " = " << len( str ) << " chars." << endl;
        return 0;
}

but it gave me this error while compiling:

Code:
/tmp/ccO2cg4E.o: In function `main':
main.cpp:(.text+0x99): undefined reference to `char (&len<char const, 13>(char const (&) [13])) [13]'
collect2: ld returned 1 exit status

Are you sure you typed it in right? The len() template certainly doesn't look like valid code to me.
 
cpjust,unfortunatelly the code is ok, that's the problem. kkk. It make no sense at all! But I assure you it works. Well, try to use the sizeof function before the len() like this:
sizeof len(array);
By the way I didn't try to use in a string array. For this kind of data the strlen() it's better. Use an array of int or float: a numeric type instead. And don't forget the sizeof. Here is the complete code:

template <typename T, int N>
char (&len(T(&)[N]))[N];

Put it into the header file and call it from the .cpp (in builder 6). I don't know nothing about the gcc environment, but I guess it's similar to the builder's interface. If you forget about the sizeof you will get the error:
"Illegal use of floating point"
Bye.
 
Nope, try this code. It won't work:
Code:
#include <iostream>

using namespace std;

template <typename T, int N>
char (&len(T(&)[N]))[N];

void func( int* array )
{
        cout << "array = " << sizeof len( array ) << " elements." << endl;
}

int main()
{
        int array[] = {1, 2, 3, 4, 5};
        func( array );
        return 0;
}
The Comeau online compiler gives this error:
Code:
"ComeauTest.c", line 10: error: no instance of function template "len" matches the
          argument list
            The argument types that you used are: (int *)
          cout << "array = " << sizeof len( array ) << " elements." << endl;
 
OK, I still can't figure out how the template works, but the important thing to note is that it will only work in the function where the array was declared. But since there aren't many people that could determine how that template works, I would stick to the simpler way that most people are used to:
Code:
int elements = sizeof( array ) / sizeof( array[0] );
 
This template defines a function named len with 1D array parameter with explicitly specified size. The template function returns a reference to an array of char with the same number of elements as an argument.

Now sizeof len(array) syntactically treated as sizeof expression where an expression is the len template function call. It's well known that the value of sizeof expression is equal to sizeof(expression_type) (an expression does not evaluated). Evidently, sizeof(char[N]) == N, that's all.

Nice (and useless) toy in the modern generic programming style...
 
cpjust, I got it. Thanks for all your help. And I agree with the ArkM it's a useless toy. I followed your link to the other page, it was very enlightening all that explanation. I think i'll never use such resource in my programs, but I had to know!
Thank u 4 everything.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top