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 &);

#endif
Where fwd_string.hpp looks like this:
#ifndef FWD_STRING_HPP
#define FWD_STRING_HPP

#include <string>

class fwd_string
{
public:
    fwd_string();
    fwd_string(const char *);
    fwd_string(const std::string &);
    std::string string;
    ...
};

#endif
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.


2 comments:

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

    ReplyDelete