473,765 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

templated pointer function for simple array

Dear all,
I realized an error in a previous post, I reproduce it here because I'm
still not sure how to solve it:

I want to make a templated function which points to one-past-the-end of
a simple array, to pass to a range constructor for a const vector.
Here is some demonstration code:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[]){
int elementSize = sizeof(parray[0]);
int arraySize = sizeof(parray);
cout<<"Inside the function:"<<end l;
cout<<"Arraysiz e: "<<arraySiz e<<" Element size: "<<elementSize< <endl;
cout<<"Pointer to array start "<<parray<<endl ;
int numel= arraySize/elementSize;
return (parray+numel);
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a);
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}

...but my templated function doesn't work at all, here is the output:

Inside the function:
Arraysize: 4 Element size: 8
Pointer to array start 0xe9ef0
Returned pointer: 0xe9ef0

Outside the function:
Array size: 40 Element size: 8
Pointer to array start: 0xe9ef0
Pointer to one-past-end: 0xe9f18

Pointer to a[5]0xe9f18

.....
I can see that inside the function, the argument parray[] has somehow
lost its 'arrayness', so the sizeof(parray) returns the size of the
pointer. Outside the function, this works fine...am i missing some
detail of syntax or is my whole philosophy crooked?

cheers

shaun
Jan 27 '06 #1
9 2197
shaun wrote:
Dear all,
I realized an error in a previous post, I reproduce it here because I'm
still not sure how to solve it:

I want to make a templated function which points to one-past-the-end of
a simple array, to pass to a range constructor for a const vector.
Here is some demonstration code:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[]){
This function takes a pointer to T.
int elementSize = sizeof(parray[0]);
int arraySize = sizeof(parray);
This will give you the size of a pointer to T.
cout<<"Inside the function:"<<end l;
cout<<"Arraysiz e: "<<arraySiz e<<" Element size: "<<elementSize< <endl;
cout<<"Pointer to array start "<<parray<<endl ;
int numel= arraySize/elementSize;
return (parray+numel);
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a);
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}

..but my templated function doesn't work at all, here is the output:

Inside the function:
Arraysize: 4 Element size: 8
Pointer to array start 0xe9ef0
Returned pointer: 0xe9ef0

Outside the function:
Array size: 40 Element size: 8
Pointer to array start: 0xe9ef0
Pointer to one-past-end: 0xe9f18

Pointer to a[5]0xe9f18

....
I can see that inside the function, the argument parray[] has somehow
lost its 'arrayness', so the sizeof(parray) returns the size of the
pointer.
Yes. It decayed into a pointer.
Outside the function, this works fine...am i missing some detail of syntax
or is my whole philosophy crooked?


You can't pass arrays by value to a function. They will always get converted
to pointers. You'd probably not want to pass the array anway, because that
would copy the whole thing (passing by value means that the passed object
gets copied into the argument of the funciton)
What you can do is pass a reference:

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

Jan 27 '06 #2
shaun wrote:
Dear all,
I realized an error in a previous post, I reproduce it here because I'm
still not sure how to solve it:

I want to make a templated function which points to one-past-the-end of
a simple array, to pass to a range constructor for a const vector.
Here is some demonstration code:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[]){
int elementSize = sizeof(parray[0]);
int arraySize = sizeof(parray);
cout<<"Inside the function:"<<end l;
cout<<"Arraysiz e: "<<arraySiz e<<" Element size: "<<elementSize< <endl;
cout<<"Pointer to array start "<<parray<<endl ;
int numel= arraySize/elementSize;
return (parray+numel);
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a);
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}

..but my templated function doesn't work at all, here is the output:

Inside the function:
Arraysize: 4 Element size: 8
Pointer to array start 0xe9ef0
Returned pointer: 0xe9ef0

Outside the function:
Array size: 40 Element size: 8
Pointer to array start: 0xe9ef0
Pointer to one-past-end: 0xe9f18

Pointer to a[5]0xe9f18

....
I can see that inside the function, the argument parray[] has somehow
lost its 'arrayness', so the sizeof(parray) returns the size of the
pointer. Outside the function, this works fine...am i missing some
detail of syntax or is my whole philosophy crooked?

cheers

shaun


Since you didn't specify a size for parray the compiler has no idea how
big it is. So you can't expect sizeof(parray) to give the size of the
array. Infact 'T parray[]' is just syntactic sugar for 'T* parray', so
you are correct in that it is just taking the size of a pointer.
Something like the following might work:

#include <iostream>
using namespace std;
double a[5] = {
2.3,4.5,6.6,8.0 ,10.0
};

template<class T, int N> T endof(T arr[N]) {
return (arr + N);
};

int main (int argc, char * const argv[]) {
double* pEnd = endof<double, 5>(a);

cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}

But so far I can only get it to work with explicit instansiation of the
endof template and that kind of defeats the point of using it in the
first place. Maybe someone with a better knowledge of the ins and outs
of templates can help?
Jan 27 '06 #3
shaun wrote:
Dear all,
I realized an error in a previous post, I reproduce it here because I'm
still not sure how to solve it:

I want to make a templated function which points to one-past-the-end of
a simple array, to pass to a range constructor for a const vector.
Here is some demonstration code:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[]){
int elementSize = sizeof(parray[0]);
int arraySize = sizeof(parray);
cout<<"Inside the function:"<<end l;
cout<<"Arraysiz e: "<<arraySiz e<<" Element size: "<<elementSize< <endl;
cout<<"Pointer to array start "<<parray<<endl ;
int numel= arraySize/elementSize;
return (parray+numel);
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a);
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}

..but my templated function doesn't work at all, here is the output:


Hm, ponder a bit about:
template < typename T, unsigned long N >
unsigned long length_of ( T const (& arg) [N] ) {
return( N );
}

#include <iostream>

const double a[] = { 2.3, 4.5, 6.6, 8.0, 10.0 };

int main ( void ) {
std::cout << length_of( a ) << '\n';
}
I am not sure if the standard guarantees that this code prints "5" because I
am a little shaky about the precise meaning of the line

const double a[] = { 2.3, 4.5, 6.6, 8.0, 10.0 };
Best

Kai-Uwe Bux
Jan 27 '06 #4
OK, thanks all...after some experimenting, I came up with:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[], long unsigned int s){
return (parray+s/sizeof(parray[0]));
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a,si zeof(a));
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}
.....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.
cheers

shaun
Jan 27 '06 #5
shaun wrote:
OK, thanks all...after some experimenting, I came up with:

#include <iostream>
using namespace std;
const double a[]={
2.3,4.5,6.6,8.0 ,10.0
};

template<class T> T * endof( T parray[], long unsigned int s){
return (parray+s/sizeof(parray[0]));
};

int main (int argc, char * const argv[]) {
const double * pEnd=endof(a,si zeof(a));
cout<<"Returned pointer: "<<pEnd<<endl<< endl;
cout<<"Outside the function: "<<endl;
cout<<"Array size: "<<sizeof(a );
cout<<" Element size: "<<sizeof(a[0])<<endl;
cout<<"Pointer to array start: "<<a<<endl;
int numElements=siz eof(a)/sizeof(a[0]);
const double * pEnd2= a+numElements;
cout <<"Pointer to one-past-end: "<<pEnd2<<endl< <endl;
cout<<"Pointer to a[5]"<<&(a[5])<<endl;
return 0;
}
....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.


What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

Jan 28 '06 #6
....

This still allows me to add extra 'magic numbers' in my const array at
the top of the file without changing any subsequent code. I'm not
entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
feels like the 'sizeof' should be redundant, but I understand why it
isn't.


What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}


Maybe I didnt properly understand, but isnt Size the number of elements?
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.
Jan 28 '06 #7
shaun roe wrote:
> ....
>
> This still allows me to add extra 'magic numbers' in my const array at
> the top of the file without changing any subsequent code. I'm not
> entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
> feels like the 'sizeof' should be redundant, but I understand why it
> isn't.


What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}


Maybe I didnt properly understand, but isnt Size the number of elements?
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.

In the syntax

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

the identifier "Size" is a template parameter. You will not need to change
anything. Try the following on your compiler, which uses the same trick:

template < typename T, unsigned long N >
unsigned long length_of ( T const (& arg) [N] ) {
return( N );
}

#include <iostream>

const double a[] = { 2.3, 4.5, 6.6, 8.0, 10.0 };

int main ( void ) {
std::cout << length_of( a ) << '\n';
}
This should print 5. Once you change it to

template < typename T, unsigned long N >
unsigned long length_of ( T const (& arg) [N] ) {
return( N );
}

#include <iostream>

const double a[] = { 2.3, 4.5, 6.6, 8.0 };

int main ( void ) {
std::cout << length_of( a ) << '\n';
}

it will print 4. As you can see, no change to the template is needed. The
compiler automatically deduces the correct value for Size (or N in my
version) upon initialization of the template at the point where it is
called.
Best

Kai-Uwe Bux

Jan 28 '06 #8
shaun roe wrote:
> ....
>
> This still allows me to add extra 'magic numbers' in my const array at
> the top of the file without changing any subsequent code. I'm not
> entirely happy that I have to pass both 'a' and 'sizeof(a)' since it
> feels like the 'sizeof' should be redundant, but I understand why it
> isn't.
What about my solution?

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}


Maybe I didnt properly understand, but isnt Size the number of elements?


Yes.
If I change the const array at the top of the file, I would have to
change all my calls to reflect the new number of members.


No, you won't. You just call it like in your original posting. The number of
elements is automatically deduced.

Jan 28 '06 #9

In the syntax

template<class T, int Size> T * endof( T (&parray)[Size]){
return parray + Size;
}

the identifier "Size" is a template parameter. You will not need to change
anything. Try the following on your compiler, which uses the same trick:


EXCELLENT! exactly what I wanted, many thanks!

shaun
Jan 28 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6576
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
2
2013
by: Thomas Matthews | last post by:
Hi, I would like to create a table (or vector) of pointers to templated functions. 1. How do I declare a typedef of a pointer to a templated function? For example, I have some functions that print out a type's name to an istream:
4
1514
by: __PPS__ | last post by:
suppose I have class that has templated operator. I want to have a few overloads/template specializations for different types. Basicly, the biggest problem I have is to be able to have this: const char a = "this is passed as an array"; const char *p = "this is passed by the address"; x_class x; x = .. whatever ..; x = ..;
204
13077
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
17
2217
by: devmentee | last post by:
Hello, I am trying to create a map/dictionary where the type of key is known ie std::string, but the value could be of any built in type. ie. int, double etc. (something along the lines of map<string, Twhere T is template argument) To hold the value type I have something like: template<class T>
2
1689
by: mattjgalloway | last post by:
I'm having some problems with a templated member function of a templated class. Unfortunately I can't replicate it with a simple example so I know something odd must be going on!!! Basically it's like this... I have a few classes all templated by one type. Inside one of the classes is a templated member function. When I try to use this templated function in another class, the compiler complains with: error: expected primary-expression...
2
2936
by: domehead100 | last post by:
I have a templated class, CDerived: template <typename TValue, typename TDraw, typename TEdit ...> class CDerived : public CBase { TValue m_Value public: TValue& GetValue() const {
9
9006
by: Bartc | last post by:
I'm having problems with the following code. I have a table of function pointers, and a function pointer variable p which steps through the functions. But I'm not allowed to increment the variable using ++p. What's the problem here? Also, I may not be interested in returning from any of these functions (each
20
2241
by: MikeC | last post by:
Folks, I've been playing with C programs for 25 years (not professionally - self-taught), and although I've used function pointers before, I've never got my head around them enough to be able to think my way through what I want to do now. I don't know why - I'm fine with most other aspects of the language, but my brain goes numb when I'm reading about function pointers! I would like to have an array of structures, something like
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9955
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9833
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7378
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.