Forward declaring std::string in C++

One type you can't forward declare in C++ is std::string
class string; // Computer says no
This does not say a lot but what it does say is that string is a class and unfortunately it's not - it's a typedef of basic_string<...>

If I compile a file containing just the line
#include <string>
then g++'s -H flag tells me that pulls in over 100 other header files! Avoiding those #includes might make an appreciable difference to build times in some C++ codebases. You can fake an std::string forward declaration by using a type wrapper. For example:
#ifndef EG_HPP
#define EG_HPP

class fwd_string; // instead of #include <string>

void eg(const fwd_string &); 
// instead of
// void eg(const std::string &);

Where fwd_string.hpp looks like this:

#include <string>

class fwd_string
    fwd_string(const char *);
    fwd_string(const std::string &);
    std::string string;

You can also use this "type-tunneling" technique to forward declare enums in C. I've never seen this used in anger in an actual codebase. It's just an idea. Caveat emptor.


  1. This blog is really informative i really had fun reading it.