Forward declaration of std::wstring

Benjamin picture Benjamin · Jan 26, 2011 · Viewed 16.5k times · Source
// This is a header file.

class MyClass; // It can be forward declared because the function uses reference.
// However, how can I do forward declaraion about std::wstring?
// class std::wstring; doesn't work.
VOID Boo(const MyClass& c);
VOID Foo(const std::wstring& s);

Answer

wilhelmtell picture wilhelmtell · Jan 26, 2011

You can't. #include <string>, you have (almost) no choice.

The reason is that wstring is defined in namespace std and is typedef'd to std::basic_string<wchar_t>. More elaborately, std::wstring is std::basic_string<wchar_t, std::char_traits<wchar_t> >. This means that in order to forward-declare std::wstring you'd have to forward-declare std::char_traits<> and std::basic_string<> inside namespace std. Because (apart from a few exceptions) the standard forbids adding definitions or declarations to namespace std (17.4.3.1/1) ultimately you can't forward-declare any standard template or type in a standard-conforming way. Specifically, this means you can't forward-declare std::wstring.

And yes, we all agree it would be convenient to have a <stringfwd> header, like <iosfwd> for <iostream>. But there isn't. <string> is also not nearly as hardcore to compile as <iostream>, but nevertheless. You have two choices: #include<string> or use an opaque pointer.