Hacker News new | ask | show | jobs
by rcxdude 4367 days ago
It depends on how you quantify cost. There isn't any performance cost, yes (which is what 'zero-cost abstractions' usually means in C++), but there is a) an increase in code size, and b) an increase in complexity/difficulty of understanding of implementation (and to some extent use). These may be good tradeoffs to make (in many of the areas where C++ is used they make sense), but I think 'zero-cost' is a disingenuous way to put it.
2 comments

How are generics more difficult to understand than hacking your own mechanism together with casts? That is something I do not understand.
That's the thing. It's easier to hack something together with casts that looks like it's okay, and not understand that you're doing something wrong.

With generics, the novice finds cases where the compiler catches them doing something wrong, so they rewrite the code using casts in a way that looks right but is subtly wrong.

The end result is code that appears correct to the novice, the novice walking away with the feeling that generics are too complicated, and a mysterious corner-case bug that bites off someone's arm once every five years.

The nature of failing to understand is that the person who fails to understand often fails to understand that they misunderstand, or often misattribute their misunderstanding. The tool gets blamed for getting in their way of writing "good" code. On the other hand, there are plenty of tools that give perfectly sensible error messages to anyone with a PhD in type theory, but a second year university student sees "Attempt to cast non-monoid endofunctor to monad. Please uninstall compiler and shave off neck beard."

There might actually be a performance cost due to increased code size (by way of increased amount of icache misses).
The implementers of MLton, an ML compiler that does C++ style monomorphization, found that after optimization the code size is actually smaller with monomorphization. That's because the specialized code is simpler and can be further optimized. So even if you have multiple specialized copies, the total is still smaller. See here: http://mlton.org/Performance