13.1 The Angle Bracket Hack

Ru-Brd

13.1 The Angle Bracket Hack

Among the most common surprises for beginning template programmers is the necessity to add some blank space between consecutive closing angle brackets. For example:

 #include <list>  #include <vector>  typedef std::vector<std::list<int> > LineTable;  // OK  typedef std::vector<std::list<int>>  OtherTable;  // SYNTAX ERROR  

The second typedef declaration is an error because the two closing angle brackets with no intervening blank space constitute a "right shift" ( >> ) operator, which makes no sense at that location in the source.

Yet detecting such an error and silently treating the >> operator as two closing angle brackets (a feature sometimes referred to as the angle bracket hack ) is relatively simple compared with many of the other capabilities of C++ source code parsers. Indeed, many compilers are already able to recognize such situations and will accept the code with a warning.

Hence, it is likely that a future version of C++ will require the declaration of OtherTable (in the previous example) to be valid. Nevertheless, we should note that there are some subtle corners to the angle bracket hack. Indeed, there are situations when the >> operator is a valid token within a template argument list. The following example illustrates this:

 template<int N> class Buf;  template<typename T> void strange() {}  template<int N> void strange() {}  int main()  {      strange<Buf<16>>2> >();  // the  >>  token is not an error  } 

A somewhat related issue deals with the accidental use of the digraph <: , which is equivalent to the bracket [ (see Section 9.3.1 on page 129). Consider the following code extract:

 template<typename T> class List;  class Marker;  List<::Marker>* markers;  // ERROR  

The last line of this example is treated as List[:Marker>* markers; , which makes no sense at all. However, a compiler could conceivably take into account that a template such as List can never validly be followed by a left bracket and disable the recognition of the corresponding digraph in that context.

Ru-Brd


C++ Templates
C++ Templates: The Complete Guide
ISBN: 0201734842
EAN: 2147483647
Year: 2002
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net