Hacker News new | ask | show | jobs
by rkts 6215 days ago
C++ version:

  template<typename T>
  void zap (T (*f)(T x), T &x) { x = f(x); }
Example:

  int square (int x) { return x*x; }

  int foo[5] = {1,2,3,4,5};

  zap<int>(square, foo[3]);   // foo is now {1,2,3,16,5}
Admittely, the <int> is a little ugly, but that can probably be fixed with Hindley-Milner (or just plain dynamic typing).
1 comments

C++ templates are similar to macros: they run at compile time to generate code, but they're a lot harder to use.
True, but in this case, the template serves a different purpose from the macro. It's there to make zap polymorphic, and would be unnecessary in a dynamic or type-inferred language. The main point is that pg's macro can be implemented as an ordinary function in a language that has references.