开发者

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

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 imple开发者_运维知识库ment this in C++, the C-style syntax used is due to memory preference.


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


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);


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜