Hacker News new | past | comments | ask | show | jobs | submit login

Here is my not-very-novel proposal for function overriding only. Its backward/forward compatible and free of name-mangling.

  void qsort_i8 ( i8 *ptr, int num);
  void qsort_i16(i16 *ptr, int num);
  void qsort_i32(i32 *ptr, int num);
  void qsort_i64(i64 *ptr, int num);
  
  #if __has_builtin(__builtin_overridable)
  __builtin_overridable(qsort, qsort_i8, qsort_i16); // qsort resolves to qsort_i8 qsort_i16
  // qsort() is forward compatible and upgradable with your own types
  __builtin_overridable(qsort, qsort_i32, qsort_i64); // qsort resolves to qsort_i8 qsort_i16 qsort_i32 qsort_i64 
  #endif
  
  i8  *ptr0; int num0;
  i16 *ptr1; int num1;
  i32 *ptr2; int num2;
  i64 *ptr3; int num3;
  
  qsort(ptr0, num0); // call qsort_i8()
  qsort(ptr1, num1); // call qsort_i16()
  qsort(ptr2, num2); // call qsort_i32()
  qsort(ptr3, num3); // call qsort_i64()



You can do that since C11 using _Generic. https://en.cppreference.com/w/c/language/generic:

  #include <math.h>
  #include <stdio.h>
 
  // Possible implementation of the tgmath.h macro cbrt
  #define cbrt(X) _Generic((X), \
              long double: cbrtl, \
                  default: cbrt,  \
                    float: cbrtf  \
              )(X)
 
  int main(void)
  {
    double x = 8.0;
    const float y = 3.375;
    printf("cbrt(8.0) = %f\n", cbrt(x)); // selects the default cbrt
    printf("cbrtf(3.375) = %f\n", cbrt(y)); // converts const float to float,
                                            // then selects cbrtf
  }


True but its very clumsy for large number of parameters. Even more importantly, its not forward compatible. For example, cbrt() cant reliably expanded to support bigints or any private types.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: