#include struct Duck { void quack(std::ostream& out) { out << "Quack!" << std::endl; } }; struct Platypus { void quack(std::ostream& out) { int* i = NULL; out << *i << std::endl; } }; template void do_quack(std::ostream& out, MaybeDuck duck) { duck.quack(out); } int main() { Duck duck; Platypus platypus; do_quack(std::cout, duck); do_quack(std::cout, platypus); }
C++ has compile-time duck typing
The C++ compiler doesn’t actually do much semantic checks in terms of whether it can “figure out” whether the type you give a template is correct.
All it does is kind of “copy-and-paste” the type you give it into the placeholder type, and sees if it compiles correctly.
Here, our two classes will both quack()
, but will not necessarily do the same
thing. One will print; the other will most likely give a segmentation fault, because you’re trying to dereference a NULL
pointer.
In other words, C++ does not do special semantic checking on templates unless you do it yourself.
Hence, this program crashes.
So what’s the solution?
There are many.
- But the Concepts Lite proposal is supposed to be a step in the right direction.
- `std::enable_if` is supposed to be a primitive that people can use to build compile-time checking.