Forward declaration of std::wstring

前端 未结 5 1978
忘了有多久
忘了有多久 2021-02-05 08:00
// 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::wstri         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 08:22

    I don't think avoiding #include gains you any real benefit, but this is how you could do it:

    namespace std {
      template
      struct char_traits;
    
      template
      struct allocator;
    
      template
      struct basic_string;
    
      typedef basic_string, allocator >
        wstring;
    }
    
    // simple test that it's compatible:
    std::wstring *p;  // incomplete type at this point, but you can have a pointer
    #include 
    int main() {
      std::wstring s = L"Hello, world!";
      p = &s;
      return 0;
    }
    

    You have to be careful of default parameters; in particular, this would not work:

    namespace std {
      template
      struct char_traits;
    
      template
      struct allocator;
    
      template,
               class Allocator=allocator >
      struct basic_string;
    
      typedef basic_string wstring;
    }
    
    #include 
    

    Compiled with the include shows the incompatibility:

    In file included from /usr/include/c++/4.4/string:41,
                     from example.cpp:15:
    /usr/include/c++/4.4/bits/stringfwd.h:52: error: redefinition of default argument for ‘class _Traits’
    example.cpp:8: note: original definition appeared here
    

提交回复
热议问题