Peeking Further into C++00X
Traditionally, the double_underscore ("__") denotes a compiler vendor-specific identifier, although it is now a universal identifier in this particular case. Here's a typical usage:
include <cstdio> namespace example { void myfunc() { std::printf("Error in function %s\n", __func__); /* ... */ } }
WG21 proposal N2220 provides further clarification of how __func__ changes over the course of the runtime environment:
namespace N { void f(); } void N::f() { } // __func__ is "f" struct S { S() : s(__func__) { } // okay, s points to "S" ~S() { } // __func__ is "~S" // __func__ is "conversion operator" operator int() { } template<class T> int g(); const char *s; }; S operator +(S,S) { } // __func__ is "operator+" template<> int S::g<int>() { } // __func__ is "g"
Tracking the PODs
The decltype feature lets you get the type of an expression, so that you can do things with the type (for example, declare more variables of that type) without knowing in advance what the type is or how to spell it.
Even More Runtime Type Information
The decltype() is a great boon to generic programming with templates, and without the runtime cost of reflection in other languages (think of TypeOf() in .NET parlance). For example, say that you're handed an iterator, and you want to know what type it refers to. Today, you need to ask the iterator for its value_type, which is a manual "traits" convention everyone is expected to follow when writing and using iterators:
template<typename Iter> void f( Iter it ) { Iter::value_type v = *it; ... }
With decltype, you could instead write:
template<typename Iter> void f( Iter it ) { decltype(*it) v = *it; ... }
This is all in service of making C++ code easier to write and with exposing fewer awkward implementation details. On a similar note, you may notice the explosion of typedefs needed to make using certain STL types legible. This is addressed by the new auto keyword that basically says "Make me a variable of the correct return type" and is bound to save hours of searching manuals and copy/paste madness. Instead of writing
for (vector<int>::const_iterator itr = myvec.begin(); itr != myvec.end(); ++itr)
the programmer can use the shorter
for (auto itr = myvec.begin(); itr != myvec.end(); ++itr)
Which form would you try to teach new programmers trying to learn C++? Yes, I think so too!
About the Author
Victor Volkman has been writing for C/C++ Users Journal and other programming journals since the late 1980s. He is a graduate of Michigan Tech and a faculty advisor board member for the Washtenaw Community College CIS department. Volkman is the editor of numerous books, including C/C++ Treasure Chest and is the owner of Loving Healing Press. He can help you in your quest for open source tools and libraries; just drop an e-mail to sysop@HAL9K.com.
Page 2 of 2