C / C ++ function using float or double or int

I have separate functions for reading from a text file (depending on whether it is int, float or double). I need the one function with an additional argument (without using the subsequent IF statement). Does anyone have any 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 driven by memory preference.

+5
source share
3 answers

You cannot overload return types. You either return the 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);
+4

ANSI C , . ++, . . StackOverflow : C C

+6

Use a template, for example:

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 like this:

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.
+2
source

All Articles