【问题标题】:Can I forward-declare a typedef when its full type will have an as-yet-unknown form?当 typedef 的完整类型具有未知形式时,我可以前向声明它吗?
【发布时间】:2013-08-18 13:01:55
【问题描述】:

问题的简单版本:

图书馆.h

 typedef library::whatever::something::complicated X;

我可以在不包含 library.h 的情况下前向声明 X 吗?


基本上我想做的是:

Foo.h:

// forward declare X

void foo (const X &);

Bar.h:

#include <library>
typedef library::type<blah>::whatever Bar;
typedef Bar X;

Foo.cpp:

#include <Foo.h>
#include <Bar.h>

foo (const X &) {...

main.cpp:

#include <Foo.h>
#include <Bar.h>

foo (X ());

前提是我不想包含&lt;library&gt;,除非我必须。假设它与其他标头交互不良,但是这些其他标头需要foo 的声明。如果不包含库,将无法调用 foo(),但这是 .cpps 需要担心的事情。

如果我想将 X 类型定义为普通的 C 类,则前向声明 C 就足够了,但这在这里行不通。

我可以将 X 前向声明为 typedef,但只有在我已经有 library::type&lt;blah&gt; 的定义(也许还有 blah 的定义)的情况下才可以使用 AFAIK。

前向声明的重点是不要#include 这些类型的定义。

这是一个相关的问题:

namespace std
{
    template <typename T>
    class vector;
}

typedef std :: vector <int> Buffer;

void foo (const Buffer &);

#include <vector> // ok until here

int main ()
{
    foo (Buffer ());
}

在这种情况下,std::vector 的前向声明与定义不兼容。让我们假设我真的真的不想#include &lt;vector&gt;(或任何外部类)。

有没有办法解决这个问题?

【问题讨论】:

    标签: c++ typedef forward-declaration


    【解决方案1】:

    您不能转发声明嵌套类,请参阅this answer

    但是,如果你的类没有嵌套,你可以这样做:

    // inside library_fwd.hpp:
    namespace library {
    namespace whatever {
    
    template <class T>
    class Something;
    typedef Something<int> IntSomething;
    
    } // namespace whatever
    } // namespace library
    

    和:

    // inside foo.cpp
    #include "library_fwd.hpp"
    void foo(const library::whatever::IntSomething&);
    

    您对 std::vector 示例的问题在于声明冲突。见std::vector。 修复:

    namespace std {
      template <class T>
      class allocator;
    
      template <typename T, class Allocator>
      class vector;
    }
    
    typedef std::vector<int, std::allocator<int>> Buffer;
    
    void foo(const Buffer &);
    
    #include <vector> // now ok
    
    int main () {
      foo (Buffer ());
    }
    

    PS 一些标准库前向声明的示例:http://en.cppreference.com/w/cpp/header/iosfwd

    【讨论】:

      【解决方案2】:

      我觉得很难做到,因为typedef library::type&lt;blah&gt;::whatever Bar;需要class library::type的完整定义,不是forward-declare可以解决的。

      【讨论】:

        猜你喜欢
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 2018-01-12
        • 1970-01-01
        相关资源
        最近更新 更多