Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jun 30, 2000

Forward Declaration for STL String Class

Question:
How do I do a forward declaration for the STL 'string' class? For example:
// Foo.hpp

class string;

class Foo
{
  string f1();
  void f2(const string& str);
  ...
}
On various compliers (MS, Sun, GNU) this produces error messages to the effect of "invalid class definition" or "conflicting class definition."

Answer:
You can't forward declare std::string because it's not the real name of this class; it's a typedef name that hides the cumbersome syntax of the following template instance:

typedef basic_string , 
allocator > string;
Because the compiler must know the exact type of a parameter in order to get the functions named correctly managed, you can't use a typedef name in a forward declaration, unless you provide the typedef declaration as well. In other words, it's OK to use a typedef name in a forward declaration as long as the compiler can see the actual type behind the typedef name. The actual type of the typedef std::string appears in , so you need to #include it in the source file that contains Foo's declaration.

Seemingly, you can place the typedef declaration given above instead of #including the header file. The problem is that this typedef uses other class templates, such as char_traits<> and allocator<>, whose declarations also need to be accessible. Therefore, at the end of the day, the only solution is to #include . Note that many compilers have features for reducing compilation time (e.g., precompiled header and cached headers), so #including the same standard header file in several files shouldn't incur longer compilation time.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap