使用float或double或int的C / C ++函数

时间:2010-12-20 16:13:27

标签: c++ c text io

我有一个单独的函数用于从文本文件中读取(取决于它是int,float还是double)。我想只需一个函数和一个额外的参数(不使用后续的IF语句)。有人有想法吗?

以下是我目前职能的形式。

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);}
编辑:我想在C ++中实现它,使用的C风格语法是由于内存偏好。

3 个答案:

答案 0 :(得分:6)

ANSI C不支持函数重载,这是您要完成的任务。但是,C ++确实如此。请参阅此处的StackOverflow链接:Default values on arguments in C functions and function overloading in C

答案 1 :(得分:4)

您不能在返回类型上重载。您可以通过引用返回值作为函数参数:

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

...

或创建模板:

template<class T> T read_column (char * file, int size_of_col);

答案 2 :(得分:2)

使用模板,例如:

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

然后这样打电话:

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.