Possible Duplicates:
C++, removing #include<vector> or #include<string> in class heade开发者_JAVA百科r Forward declare an STL container?
I want to forward declare std::string, by the way, can I forward declare a struct?
std::string is a typedef so you cannot just forward declare it. You could look up the exact declaration, forward declare that and define the typedef yourself, but then you'd also have to forward declare char_traits and allocator. So this should might work, although it's not supposed to*:
namespace std
{
template< class T, class Traits, class Allocator >
class basic_string;
template< class T >
struct char_traits;
template< class T >
class allocator;
typedef basic_string< char, char_traits< char >, allocator< char > > string;
}
but in the end you're probably better off including . I'm also unsure whether these declarations are exactly the same on all platforms, not to mention the problems it would cause should the declaration in the string header ever change.
*see comment below
in general so as to forward declare the class of a namespace you do it this way:
namespace MyOtherNamespace
{
class MyForwardedClass;
}
namespace MyNamespace
{
MyOtherNamespace::MyForwardedClass * pClass;
}
but I suspect there may be some limitation concerning std::
, not sure though, I am going to check. Because I kind of remember some collisions due to typedefs...
Simple answer: don't do it. Never try to 'forward declare' elements from the standard library (or from boost or cgal etc)... you will shooot yourself in the foot. The above post already states, that you'd need to forward declare the complete type definition. This can easily lead to conflicts on other platforms or different implementations of the standard library.
This is a traditional problem of c++. Unreflected includes of std or boost lead to inacceptable compilation times, wild propagation of errors from template instantiations and so on. I have seen it newly in one of our projects where people having no clue were at work. You have several choices to avoid or hide the dependencies:
- Don't expose these elements in your API, use (const) char*, for example ...
- Write generic code, which does not need to now the run-time type
- Write interfaces which encapsulate functionality of these elements and allows you to move the dependencies into source files.
The best variant would use a combination of all three.
精彩评论