Professional Documents
Culture Documents
”
Charles McCabe, San Francisco Chronicle
Open Channel
110 Computer
void f(vector<int>& vi, list<string>& ls)
{
int n1 = count(vi.begin(),vi.end(),7);
int n2 = count(ls.begin(),ls.end(),”seven”);
value “seven” in a list of strings. // ...
There are ways of achieving this in }
every language that allows overloading. (a)
Given templates, we can write a single
function that handles both calls, as template<class Iter, class T>
shown in Figure 1b. This template will int count(Iter first, Iter last, T value)
expand into optimal code for the two {
calls. This count() is roughly equiva- int c = 0;
lent to the standard-library count() so while (first!=last) {
a user will not have to write it. The if (*first == value) c++;
count() function itself relies on over- ++first;
loading: Obviously, the equality opera- }
tor == is overloaded for integers and return c;
strings (with the obvious meaning). In }
addition, * and ++ are overloaded to (b)
mean “dereference” and “refer to next
element” for the iterator types for vec-
Figure 1. Changes in relationships between features can make fundamental new programming
tors and lists; that is, * and ++ are given
techniques feasible: (a) A count algorithm for counting the number of occurrences of the value
the meaning they have for pointers.
7 in a vector of integers, as well as the number of occurrences of the value “seven” in a list of
This definition of count() illustrates
strings becomes (b) a single function that handles both calls using a template.
a couple of the key techniques used in the
containers and algorithms part of the C++
standard library. These techniques are template<class Iter, class Predicate>
useful, and they are not trivially discov- int count_if(Iter first, Iter last, Predicate pred)
ered given only the basic language rules. {
Consider a slightly more advanced int c = 0;
variation of the count() example while (first!=last) {
shown in Figure 2a. Instead of counting if (pred(*first)) c++;
occurrences of a value, count_if() ++first;
counts the number of elements that ful- }
fill a predicate. For example, we can return c;
count the number of elements with a }
value less than 7 as shown in Figure 2b. (a)
Generalizing this technique to handle
comparisons with any value of any type bool less_than_7(int i) { return i<7; }
requires us to define a function object—
that is, a class whose objects can be void f2(vector<int>& vi, list<int>& li)
invoked like functions, as shown in {
Figure 3a. The constructor stores a ref- int n1 = count_if(vi.begin(),vi.end(),less_than_7);
erence to the value we want to compare int n2 = count_if(li.begin(),li.end(),less_than_7);
against, as in Figure 3b, and the applica- // ...
tion operator (operator()) does the }
comparison. In other words, count the (b)
number of elements in vi that have a
value less than the integer 7, and count
Figure 2. More advanced variation of the count example that (a) counts the number of elements
the number of elements in ls that have
that meet a predicate—for example, (b) the number of elements with a value less than 7.
a value less than the string “seven.”
It may be worth mentioning that the
code generated is very efficient and in techniques for using templates and over- Language features are fundamentally
particular does not use function calls—or loading—and that, of course, is part of boring in isolation and they can distract
similar relatively slow operations—to the purpose of presenting the examples from good system building—only in the
implement comparisons, fetching the here. However, the bottom line is that context of programming techniques do
next element, and so forth. these techniques allow you to write effi- they come alive.
Undoubtedly, this code will look cient, type-safe, and generic code. People
strange to someone who is not a C++ pro- familiar with functional languages will The Standard Library
grammer and even to C++ programmers note that these techniques are similar to Computer: How was the Standard
who have not yet internalized the latest techniques pioneered in those languages. Library defined and what impact will it
112 Computer
int main()
{
cout << “Please enter your first name:\n”;
string name;
oriented” really is, and discussions rarely cin >> name; // read into name cout
account for experience sufficiently. Much << “Hello“ << name << “!\n”;
of “the trouble with OO” comes from }
people with no significant OO experience
approaching an ambitious project with Figure 4. Simple “Hello” program using Standard Library features to perform its task simply.
some partially understood—yet dog-
matic and typically limited—notion of
what OO code must look like. the criteria for “goodness” (easy to JAVA AND C++
So what is OO? Certainly not every understand, flexible, efficient) are a Computer: That same argument for sim-
good program is object-oriented, and not recursive descent parser, which is tradi- plicity could conceivably be extended to
every object-oriented program is good. If tional procedural code. Another exam- Java, which might explain the 700,000
this were so, “object-oriented” would ple is the STL, which is a generic library Java programmers that Sun claims (com-
simply be a synonym for “good,” and the of containers and algorithms depending pared to 1.5 million C++ programmers).
concept would be a vacuous buzzword crucially on both traditional procedural You maintain that Java is not the language
of little help when you need to make code and on parametric polymorphism. you would have designed even if C++
practical decisions. I tend to equate OOP I find languages that support just one needn’t be compatible with C. What else
with heavy use of class hierarchies and programming paradigm constraining. do you have to say after having been asked
virtual functions (called methods in some They buy their simplicity (whether real this question for the thousandth time?
languages). This definition is historically or imagined) by putting programmers Stroustrup: These days, I’m always asked
accurate because class hierarchies and into an intellectual straitjacket or by about Java, and it is very hard for me to
virtual functions together with their pushing complexity from the language respond. If I say something negative, I
accompanying design philosophy were into the applications. This is appropriate sound ungracious; if I say something pos-
what distinguished Simula from the other for special-purpose languages, but not itive, I feed into the commercial hype that
languages of its time. In fact, it is this for general-purpose languages. surrounds Java and the unfortunate anti-
aspect of Simula’s legacy that Smalltalk I have often characterized C++ as a gen- C++ propaganda that emanates from
has most heavily emphasized. eral-purpose programming language with parts of the Java community.
Defining OO as based on the use of a bias toward systems programming. I encourage people to consider the two
class hierarchies and virtual functions is Think of it as “a better C” that supports languages according to their design crite-
also practical in that it provides some ria and not just in the context of com-
guidance as to where OO is likely to be • data abstraction, mercial rivalries. I outlined the design
successful. You look for concepts that • object-oriented programming, and criteria for C++ in detail in The Design
have a hierarchical ordering, for variants • generic programming. and Evolution of C++, and Java doesn’t
of a concept that can share an imple- even start to meet those criteria. That’s
mentation, and for objects that can be Naturally, this support for more than fine as long as programmers consider Java
manipulated through a common inter- one approach to programming causes as a programming language among oth-
face without being of exactly the same more complexity than supporting only ers and not a panacea. After all, C++ isn’t
type. Given a few examples and a bit of one approach. I have noticed that this a perfect match for Java’s design aims
experience, this can be the basis for a very viewthat there are design and pro- either. However, when Java is promoted
powerful approach to design. gramming approaches with domains in as the sole programming language, its
However, not every concept naturally which they are the bestoffends some flaws and limitations become serious.
and usefully fits into a hierarchy, not every people. Clearly, I reject the view that there Here are a few examples where the cri-
relationship among concepts is hierarchi- is one way that is right for everyone and teria applied to developing C++ led to
cal, and not every problem is best for every problem. People who passion- significant differences. Unlike Java, C++
approached with a primary focus on ately want to believe that the world is supports
objects. For example, some problems really basically simple react to this with a fury
are primarily algorithmic. Consequently, a that goes beyond what I consider appro- • the ability to effectively compose a
general-purpose programming language priate for discussing a programming lan- program out of parts written in dif-
should support a variety of ways of think- guage. After all, a programming language ferent languages,
ing and a variety of programming styles. is just one tool among many that we use • a variety of design and program-
This variety results from the diversity of to construct our systems. ming styles,
problems to be solved and the many ways The ideal way of resolving the two • user-defined types with efficiencies
of solving them. C++ supports a variety of views would be to have a language that that approach built-in types,
programming styles and is therefore more provides a set of simple primitives from • uniform treatment of built-in and
appropriately called a multiparadigm, which all good programming styles can user-defined types, and
rather than an object-oriented, language be efficiently supported. This has been • the ability to use generic containers
(assuming you need a fancy label). repeatedly tried but not—in my opin- without runtime overhead (for
Examples of designs that meet most of ion—achieved. example, the STL).
I designed C++ so programmers could Given C++’s relative maturity at this I’d rather not specifically “rate” the
write code that is both elegant and efficient. point, how would you rate the available available C++ tools. They are better than
For many applications, C++ is still the best C++ development tools and what still they were, and most often as good or bet-
choice when you don’t want to compro- needs to be done to improve? ter than any tools for any other language.
mise between elegance and efficiency. Stroustrup: First, I’d like to see the basic However, as a programmer, I am natu-
I wonder how people count “pro- tools such as compilers, debuggers, pro- rally impatient for more and better qual-
grammers.” Is a student a programmer? filers, database interfaces, GUI builders, ity tools. Personally, I look forward to
Is every compiler shipped counted as a CAD tools, and so forth fully support the better tools for analyzing C++ source
programmer? I understand the number ISO standard. For example, I’d like to get code. I also hope that C++ implementa-
quoted for C++; it is conservative and a database query result as an STL con- tion vendors will spend a slightly larger
plausible. It is a good approximation of tainer or an istream of appropriately fraction of their budgets on improving
the number of C++ implementations sold typed objects. Tool vendors have made a the quality and performance of their
for real money last year. I wonder if Sun’s good start, but have much work to do in compilers rather than concentrating too
Java number is as solid. Incidentally, tools that depend on compilers and other heavily on novelties. Real improvements
based on the few hard numbers I have source code analyzers. in compilers are relatively cheap com-
found—such as compiler sales, book My list of basic tools is a partial answer pared to what is spent on a new release
sales, and C++ course attendance—I esti- of a complete C++ implementation.
mate that the C++ user population is However, I fear that unless major users
growing at 10 to 20 percent a year. Java has borrowed start demanding conformance testing
And no, I’m not a Java fan. I dislike much from C++, but not and benchmarking, vendors will spend
hype, I dislike marketing of program- as much as is often resources on what looks better in an
ming tools to nonprogrammers, I dislike claimed and not with as advertisement.
proprietary languages, and I like lots of
much taste and
programming languages. On the techni- THE FUTURE
cal side, Java never gave me the “Wow,
understanding as one Computer: I know you’ve been heavily
that’s neat!” reaction that I have had could have wished for. involved in the C++ standards process,
with many other languages. It provides but what other projects are you involved
popular language features in a form that in currently and how will you continue
I consider limiting. to the question about what has changed: working to evolve C++?
Java has borrowed much from C++, Over the past few years, large numbers Stroustrup: I’m suffering from having
but not as much as is often claimed and of programmers have come to depend on successfully completed a very large pro-
not with as much taste and understand- elaborate tools to interface code with sys- ject. The ISO C++ standard is done. The
ing as one could have wished for. To tems facilities. These tools are essential to third edition of The C++ Programming
deliver on some of the key promises relieving programmers of tedious and Language is there to acquaint serious
made for it, Java must grow. This evo- error-prone tasks, but come at a risk of programmers with what Standard C++
lution may compromise Java’s claim of the programmers (and their employers) has to offer and how best to use it. And
being simpler than C++, but my guess is becoming captives of their tool suppliers. Design and Evolution documents the
that the effort will make Java a better Often, these tools are far more complex design decisions that shaped C++. There
language than it is today. Currently, Java than a traditional programming lan- is more to be done, but nothing that
seems to be accumulating language fea- guage, and there are few standards. requires a full-time language designer.
tures and “standard” libraries at quite I would encourage nonproprietary Now is the time to enjoy the flexibility
a pace. I’m looking forward to seeing standards for tools and libraries. In the and power of C++ by writing code,
what the Java version of templates will short term, say 10 years, many such stan- rather than focusing on possible changes.
look like; as far as I know Sun hasn’t yet dards will be industry standards rather Apart from that, I’m taking the oppor-
blessed any of the dozen or so dialects. than formal ISO or IEEE standards, but tunity to learn a few things—a couple of
As Java and its community matures, it it is essential for the software industry’s new languages and something about how
will hopefully adopt a sensible live-and- health that key interfaces be well-specified software is used in a large business—and
let-live philosophy. This would allow and publicly available. With the increasing planning some experiments in distributed
Java to take its place as one language importance of standards for system-level computing. ❖
among many in the tool chest of profes- objects such as COM and CORBA, it is
sional programmers. particularly important that the C++ bind-
ings to those be clean, well documented,
TOOLS and simple to use. Unfortunately, such
Computer: In what ways have systems “standards work”which is beneficial to Bjarne Stroustrup is head of the large-
changed over the past few years, and everybodyis neglected because it pro- scale programming research department
what still needs to be done in the C++ vides short-term competitive advantages at AT&T; bs@research.att.com;http://
arena and in systems design in general? to nobody. www.research.att.com/~bs/
114 Computer