我很好奇我的typedef方法对我的构建的影响。

请考虑以下示例。

#include "SomeClass.h"

class Foo
{
    typedef SomeClass SomeOtherName;

    SomeOtherName* storedPointer;

    void setStoredPointer(SomeOtherName* s);
}

void Foo::setStoredPointer(SomeOtherName* s)
{
    storedPointer = s;
}

每当我最终遇到上述情况时,这会将typedef驱动到头文件中,因此需要我在头文件中#include它。我担心缺乏前瞻性声明可能会导致更长的构建时间。

根据这篇文章的评论:

在C ++中转发typedef的声明

我可以转发声明类,typedef引用或指针,然后#include在.cpp文件中。这应该允许更快的构建时间。我的结论是否正确?

如果是这样,我最终会得到一个typedef,例如:

typedef SomeClass* SomeOtherNamePtr;
typedef SomeClass& SomeOtherNameRef;
typedef const SomeClass* SomeOtherNameConstPtr;
typedef const SomeClass& SomeOtherNameConstRef;

这对我来说看起来不是很干净的代码,而且我认为我已经阅读了文章/帖子(不一定是在SO上)推荐反对这一点。

你觉得这个可以接受吗?更好的选择?


更新: 使用Michael Burr的答案,我只能解决指针和引用的情况。但是,当我尝试在我的函数中使用sizeof()时,我遇到了一个问题。例如,假设该类具有以下功能:

//Foo.h
class Foo
{
    typedef class SomeClass SomeOtherName;

    void doSomething(const SomeOtherName& subject)
}

//Foo.cpp
#include "Foo.h"
#include "SomeClass.h"
void Foo::doSomething(const SomeOtherName& subject)
{
    sizeof(subject); //generates error C2027: use of undefined type 'SomeClass';
    sizeof(SomeClass); //generates same error, even though using the sizeof()
                       //the class that has been #include in the .cpp.  Shouldn't
                       //the type be known by now?
}

或者,这可行。

//Foo.h
class SomeClass;
class Foo
{
    void doSomething(const SomeClass& subject)
}

//Foo.cpp
#include "Foo.h"
#include "SomeClass.h"
void Foo::doSomething(const SomeClass& subject)
{
    sizeof(subject);
    sizeof(SomeClass);
}

我正在使用Microsoft Visual C ++ 6.0。这是编译器的错误还是一般违反标准?

在出现错误的示例中,请注意sizeof(SomeClass)是typedef的原始类,而不是在Foo中创建的新typedef类型。我很惊讶在typedef中执行前向声明会限制我对typedef这个类做任何事情的能力。


跟进: 刚刚使用XCode编译器测试它,我相信我的sizeof问题是Visual C ++ 6.0编译器问题。我猜测XCode编译器可能是正确的,但我目前还没有其他任何东西可以尝试。所以,虽然这提供了丰富的信息,但我个人对我目前的任务感到不满,因为最好的答案对我的情况不起作用。

有帮助吗?

解决方案

typedef class SomeClass SomeOtherName;

为你做诀窍?

这样,仅对指针或引用使用 typedef 的编译单元不需要 #include SomeClass 标头。

其他提示

  

我的结论是否正确?

是。您引用的问题中的答案之一表明您可以:

//forward declaration instead of #include "SomeClass.h"
class SomeClass;
//now this works even without #include "SomeClass.h"
typedef SomeClass SomeOtherName;
  

这对我来说看起来不是很干净的代码

我没有看到你的typedef添加任何值;相反,我可能会转发声明 SomeClass ,然后直接使用' const SomeClass& '。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top