You are here:

C++/C++ template

Advertisement


Question
Hello, I'm trying to do something like:

template <typename T, template <typename X ,typename = std::allocator<X> > class C> class A {
 C<T> a;          // Ok
 C<T>::iterator i;   // Error on GCC (G  ), Ok on BCC
...
};

in code:
A<int ,std::vector> xxx;

Works fine with BCC, with GCC I got:
error: expected ;' before "i"

How similar functionality can be implemented for GCC?

Thank you.

Answer
In template definitions the compiler cannot tell for sure which names are types and which are not if those names are dependent on a template parameter. These are called dependent names. The default is to assume that such names do not refer to a type. If a dependent name does refer to a type you have to explicitly  tell it so by prefixing the name by typename in your case C<T>::iterator is a dependent type name and not so it should be prefixed by typename:

   template
   < typename T
   , template <typename X ,typename = std::allocator<X> > class C
   >
   class A
   {
   public:
     C<T> a;          // Ok

   // Tell compiler that C<T>::iterator is a type name
     typename C<T>::iterator i;
   };

This fixed the problem when I compiled you example using g++ 4.0.2.

You could point out that it is obvious that you meant a type in your case because that is the only thing that could go in such a position and make sense. However problems occur when one template refers to names in another template. Template definitions can be explicitly specialised, meaning that for some template parameter combinations different definitions can apply. So for example if some member function in class template A uses a name from class template B it may be able to determine whether it is a type or a not. However, if later there exists an explicit specialisation of B for some type that declares the name differently then in this case the meaning of the code in A could be different. Here is an example taken from "C++ Templates The Complete Guide" by David Vandevoorde and Nicolai M. Josuttis (which I think is a very good investment if you are going to be using templates a lot!):

   template <typename T>
   struct Trap
   {
       enum { x };    // (1) x is not a type here
   };

   template <typename T>
   struct Victim
   {
       int y;
       void proof()
       {
       // (2) declaration or multiplication?
         Trap<T>::x * y;  
       }
   };

   template <>
   struct Trap<void>
   {
       typedef int x;  // (3) x is a type here
   };

   void boom( Victim<void>& bomb )
   {
       bomb.proof();
   }

   void boom( Victim<int>& bomb )
   {
       bomb.proof();
   }

I have used struct in place of class and public for brevity, corrected the signature of boom as noted in the book errata at http://www.josuttis.com/tmplbook/ (2nd - 4th printings, page 130), and added an overload of boom to show using Victim with an alternate type.

The text in the book points out that when parsing Victim::proof() the compiler has to determine whether the line after comment (2) is a declaration or a multiplication. It could look at the known definitions of the Trap class template which, as noted by comment (1) shows x to not be a type and this would lead it to conclude that the statement after comment (2) is a multiplication. Sometime later the compiler finds and compiles the explicit specialisation of the Trap class template, in which x, at comment (3), is declared as a type and this conflicts with the compiler's previous assumption about the meaning of the statement at (2).

Hence the compiler cannot make any assumption on what the correct meaning of dependent names are. Any such assumption can be overturned by later code. So the position taken by the compiler is that all such dependent names are assumed to name a non-type identifier, unless told otherwise. You can tell the compiler that a dependent name is a type using typename, as was required in your example. The other possibility is that the name refers to a template, and in these cases you prefix the name with the keyword template rather than typename.

The use of typename and template in this fashion came about with the C++ standard in 1998 (maybe a little earlier for compilers at the bleeding edge of C++ features!) and I know from painful personal experience that different compilers have different ideas as to when typename is allowed, when it is not and when it is compulsory. I recently spent a fun few hours tidying up some code that had only been built using MSVC++ 8 (the 2005 edition) so that it would build under g++ 4.0.2. The main points of disagreement were that MSVC++ was more relaxed about allowing typename where g++ thought it should not be used. I suspect that g++ is closer to the requirements of the C++ standard.

In some cases getting one piece of code to compile on all compilers you require is not easy as what compilers are happy with can be mutually exclusive. I have had to resort to checking pre-defined macros that identify which compiler I am using and defining macros for cases where typename is compulsory by one compiler and forbidden by another, defining the macros to expand to either typename or nothing as appropriate.

Older compilers tend to do very little checking of templates when they are defined, doing the full check when concrete specialisations are created. They may not even support the use of typename and template in the context under discussion here. Note that knowing the compiler type is not enough, as newer versions of the same compiler will have (hopefully) better C++ standard support. This is why I stated the version of compilers involved.

I am not very familiar with the Borland compilers (I presume this is what you meant by bcc), and do not have one to hand to try your code out on. So I am not able to advise on how they handle typename in this context or even which version supports it.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.