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

5
我有不同的函数来读取文本文件(根据它是整数,浮点数还是双精度)。我希望只有一个函数,加上额外的参数(而不使用后续的 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风格的语法是因为内存偏好。


我移除了C++标签,因为存在IOStreams和函数重载,如果不使用它们,其代码风格几乎保证这是仅限于C的代码。 - Puppy
2
最好使用 const char *file - user502515
size_of_col是指您传递给函数的值(float、double、int)的大小吗? - Nathan Garabedian
size_of_col = 列中的条目数。 - swarm999
3个回答

6

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

仅通过模板化的返回类型,这是否可能? - user502515
1
可以仅对返回类型进行模板化,但这样得到的结果将不比具有不同名称的多个函数好多少,因为编译器无法为您推断返回类型。 用户代码将如下所示: double d = read_column<double>( "file.txt", 10 );--即用户代码必须显式指定类型。 - David Rodríguez - dribeas
@user502515: 是的。它将被称为read_column<int>read_column<float>read_column<double>。这比使用不同名称的多个函数要好得多,因为对于所有三个函数,都有一个单一的源,其中使用T代替要读取的类型。 - Steve Jessop
在您的第一种选择中,我认为最后一个参数需要是float*&,因为(出于某种原因)提问者的函数返回指向malloced数组的指针。 - Steve Jessop
据推测,您可以结合这两种方法,使用一个以引用T*&为参数的模板。 - caf

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接