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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A function that operates on different data types

Status
Not open for further replies.

smithpd

Programmer
Jul 8, 2002
20
0
0
US
I am reading a disk file that has a header record that defines the data type of a data array that follow in the file. It could be char, short, or long. I look at the header and then malloc() storage for the following data, which returns a pointer to an array of the approprate data type (malloc must be inside an if() statement). I can read the file data into that allocated storage with no problem. Now I want to call a function that operates on this data. It calls other functions, etc. Is there a simple method to pass the pointer to the data of different types and allow the receiving functions to process the data as an array, to operate on data[ ]?

I tried template functions and they propagated throughout the code to make a real mess that I would rather not deal with. Every function call needs to be in an if() statement to call the appropriate instance of the template function.

I thought about creating a pure virtual base class and using polymorphism, overloading the [] operator, but I have read that this will not work because polymophism requires that the return type of overloaded functions be the same. In the case of the [ ] operator, the return type is not the same: it is a reference to data of the given type, data_type&, which varies in each instance.

I thought about passing a void*, but then each referece to data[] would need to be in an if statement, to use a cast of the void * pointer to a pointer of the correct type (as I understand it).

Is there a simple way to do this? What am I missing?
 
Have you considered using a struct with a union and a constructor that takes a parameter to set the data type and size?

As for the rest this really is a job for templates.

HTH
William
Software Engineer
ICQ No. 56047340
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top