April 2, 2009

If It Floats Like An Octopus

"C++: an octopus made by nailing extra legs onto a dog."

C++ is often referred to as a statically-typed language - it aggressively checks types at compile time (and, in the case of anything STL-related, spews out monstrous-looking errors.) By comparison, many "scripting" languages (and I use that word cautiously, since these are proving to be powerful application development languages in their own right!) such as Python and PHP support what is known as duck typing. Many rail against this, arguing that it leads to unmaintainable code and nasty runtime errors.

That aside, C++ does have support for duck typing - in its template system. Consider:

#include <iostream>
using namespace std;
template <class T> void p(const T& t) { t.print(); }
struct A { void print() const { cout << "A!" << endl; } };
struct B { void print() const { cout << "B!" << endl; } };
struct C { };
int main() {
   A a; B b; C c;
   p(a);        // "A!"
   p(b);        // "B!"
   //p(c);      // compile-time error

The global function p() enforces no type restrictions on the template class T; all it requires is that T implement void T::print() const, as A and B do. Also, note that p(c) causes a compile-time error, not a runtime error! There is a tradeoff, naturally: the compiler creates a separate copy of p() for each type that it's invoked with (g++ -S for the gory details!), so extensive use of this technique can easily balloon your object files.

No comments:

Post a Comment