Alternatives to function overloading in C

拜拜、爱过 提交于 2019-12-01 14:31:47

The naive, simple way to do it:

#include <stdio.h>

void func_int (int x) { printf("%d\n", x); }
void func_char (char ch) { printf("%c\n", ch); }

#define func(param)          \
  _Generic((param),          \
    int:  func_int(param),   \
    char: func_char(param)); \

int main() 
{
  func(1);
  func((char){'A'});
}

This is type safe but only supports one parameter. At a glance this might seem insufficient.

If you want completely variable parameter lists, then you'd have to implement a way to parse variadic macros and __VA_ARGS__. Likely, it is possible. Likely it is ugly. Likely, this is not what you need.

The need for function overloading in general might be "an XY problem". You need to have functions with different parameter sets and you are convinced that function overloading is the best way to solve it. Therefore you ask how to do function overloading in C. Which is, as it turns out, not necessarily the best way.

A much better way would be to make a function interface with a single struct parameter, which can be adapted to contain all the necessary parameters. With such an interface you can use the above simple method based on _Generic. Type safe and maintainable.

This we can exploit using array concepts.

1) Pass all the arguments(values) i.e. double constants as arrays, like this

double arr[]={a,b,c,h};
int trial_no; //1 or 2
bisect_area_tria2(..., &nthr,arr, &S, area_tria2_nthr,trial_no);

There in that function use array reference like this:

void area_tria2_nb(..., int *nb, double arr[], double *S,int trial_no) {

    // change parameter 'nb'
    ...
if(trial_no==2){
    S = sqrt(s*(s-arr[0])*(s-arr[1])*(s-arr[2]));
}
else
      S = 0.5*arr[1]*arr[3];
}

For 'nb' or 'nthr', simply pass the address of the corresponding variable. This is just the reference, may not be exact for your situation. If any doubt, ask again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!