【问题标题】:Forward declaring a typedef for a template class [duplicate]转发为模板类声明 typedef [重复]
【发布时间】:2014-05-10 20:31:57
【问题描述】:

我知道 typedef 不能在 C++ 中前向声明,但我想知道以下问题的最佳解决方案是什么。我有一个像这样声明MyClass 的头文件:

#include <TemplateClassHeaders>

struct MyStruct
{
    // ...
}

typedef Really::Long::TemplateClassName<MyStruct> MyClass;

MyClass 用在很多地方,但大多只是作为通过 Qt 信号槽机制传递的指针。只需要一个前向声明,但由于 MyClass 是一个不起作用的 typedef。有没有办法避免将 myclass.h 添加到使用指向 MyClass 的指针的每个标头中?

【问题讨论】:

  • class MyClass;Google,或者甚至在您输入问题时查看建议的 SO 链接,应该会显示 stackoverflow.com/questions/804894/…
  • @mah 再想一想或至少阅读整个问题,而不是自动投反对票并将我指向一个类似的问题(没有模板和模板参数)会向您揭示class MyClass将不起作用(即使不涉及模板,也不会起作用,因为重新声明)。
  • 如果不涉及模板,@Marian, class MyClass; 将起作用。
  • @Marian @MattMcNabb class Myclass; 不起作用,即使不涉及模板。它会愉快地编译,但任何使用MyClass 的代码都会默默地使用class MyClass 而不是typedef,因此例如声明为采用MyClass * 参数的函数将根据typedef 是否可用而受到不同的破坏,从而导致链接时错误。
  • 我发现它真的很烦这个问题作为一个问题的副本被关闭,没有一个答案解决了这个问题的核心问题,即 typedef 用于一个模板实例(可能参数类型为另一个模板实例),其类名可能(实际上)不可能写下来。

标签: c++ templates typedef forward-declaration


【解决方案1】:

您不能前向声明 typedef。但是如果你前向声明它所依赖的类,TemplateClassNameMyStruct,你应该能够定义MyClass

namespace Really {
  namespace Long {
    template <typename>
    class TemplateClassName;
  }
}

class MyStruct;

typedef Really::Long::TemplateClassName<MyStruct> MyClass;

MyClass *p = 0;

【讨论】:

  • 这个丑陋的、不必要的混乱需要修复。我们拥有十亿倍以上的高级功能,但是像“嘿,按名称使用这个东西”这样简单的事情基本上是不可能的 - 需要其他人定义的类型的内部知识基本上重新创建 typedef!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多