Comment

Comment by wasmperson

> Lack of support for type-safe containers (need to be hack toghether via macros)

Are templates really so much better than macros that the latter deserve to be called a "hack"? The following two examples are both type-safe and have roughly the same semantics and #LoC:

Macros:

  // pair.h
  struct id(pair) { T a, b; };
  static inline struct id(pair) id(make_pair)(T a, T b){
    return (struct id(pair)){ .a = a, .b = b };
  }
  #undef id
  #undef T

  // main.c
  #include <stdio.h>
  #define T int
  #define id(n) n ## _int
  #include "pair.h"
  int main(void){
    struct pair_int p = make_pair_int(12, 13);
    printf("%d %d\n", p.a, p.b);
  }
Templates:

  //pair.h
  template<typename T>
  struct pair { T a, b; };
  template<typename T>
  pair<T> make_pair(T a, T b){
    return (pair<T>){ .a = a, .b = b };
  }

  //main.cpp
  #include <stdio.h>
  #include "pair.h"
  int main(void){
    pair<int> p = make_pair(12, 13);
    printf("%d %d\n", p.a, p.b);
  }
parent wasmperson 2 months ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton