5

I have seperate functions for reading from a text file (depending on whether its an int, float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}


double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}


int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

swarm999
  • 55
  • 1
  • 4

3 Answers3

6

ANSI C doesn't support function overloading, which is what you are trying to accomplish. C++ does, however. See the StackOverflow link here: Default values on arguments in C functions and function overloading in C

Community
  • 1
  • 1
4

You can't overload on return types. You either return value by reference as a function parameter:

void read_column (char * file, int size_of_col, float&);
void read_column (char * file, int size_of_col, int&);

...

or create a template:

template<class T> T read_column (char * file, int size_of_col);
Gene Bushuyev
  • 5,512
  • 20
  • 19
  • Is that possible with just the return type being templated? – user502515 Dec 20 '10 at 16:37
  • 1
    It is possible to only template the return type, but you will be left with something that is not that much better than multiple functions with different names, as the compiler will not be able to deduct the return type for you. User code will look like: `double d = read_column( "file.txt", 10 );` --i.e. user code will have to make the type explicit. – David Rodríguez - dribeas Dec 20 '10 at 17:02
  • @user502515: yes. It will be called as `read_column`, `read_column` or `read_column`. It's considerably better than multiple functions with different names, because there's single source for all three functions, using `T` in place of the type to be read. – Steve Jessop Dec 20 '10 at 17:02
  • in your first option, the last parameter needs to be `float*&`, I think, because (for whatever reason) the questioner's function returns a pointer to a malloced array. – Steve Jessop Dec 20 '10 at 17:06
  • Presumably you could combine the two approaches, and use a template that takes a reference `T*&`. – caf Dec 20 '10 at 23:29
2

Use a template, like:

template<typename Type>
Type * read_column(char * file, int size_of_col)
{
    Type* col = (Type*) malloc(size_of_col * sizeof(Type));
    ...
    return(col);
}

Then call as so:

int    * col_int    = read_column<int>   ("blah", 123);
float  * col_float  = read_column<float> ("blah", 123);
double * col_double = read_column<double>("blah", 123);
etc.
Inverse
  • 4,408
  • 2
  • 26
  • 35