MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Summary

One of the greatest weaknesses of C++ templates will be shown to you when you try to write code that uses templates, especially STL code (introduced in the next two chapters), and start getting compile-time error messages. When you’re not used to it, the quantity of inscrutable text that will be spewed at you by the compiler will be quite overwhelming. After a while you’ll adapt (although it always feels a bit barbaric), and if it’s any consolation, C++ compilers have actually gotten a lot better about this – previously they would only give the line where you tried to instantiate the template, and most of them now go to the line in the template definition that caused the problem.

The issue is that a template implies an interface . That is, even though the template keyword says “I’ll take any type,” the code in a template definition actually requires that certain operators and member functions be supported – that’s the interface. So in reality, a template definition is saying “I’ll take any type that supports this interface.” Things would be much nicer if the compiler could simply say “hey, this type that you’re trying to instantiate the template with doesn’t support that interface – can’t do it.” The Java language has a feature called interface that would be a perfect match for this (Java, however, has no parameterized type mechanism), but it will be many years, if ever, before you will see such a thing in C++ (at this writing the C++ Standard has only just been accepted and it will be a while before all the compilers even achieve compliance). Compilers can only get so good at reporting template instantiation errors, so you’ll have to grit your teeth, go to the first line reported as an error and figure it out.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru