假设我有以下课程:
foo.h中:
class MyVectorClass;
class Foo {
public:
MyVectorClass get();
...
}
遵循共同商定的转发模式声明可以向前声明的所有内容,并且由于MyVectorClass
仅用作方法的返回类型,因此MyVectorClass
是前向声明的。然后,此类的任何用户都应包含MyVectorClass.h
,以便能够使用方法get
。
Bar.cpp:
#include "Foo.h"
#include "MyVectorClass.h"
Foo foo;
...
MyVectorClass result = foo.get();
为了使用类Foo
我们需要包含一些额外的标题,这让我质疑这里的前向声明的想法。如果我使用auto而不是MyVectorClass
,这对我来说更加困惑,这是更好的,因为我并不真正关心MyVectorClass
,任何具有类似矢量的界面的东西对我来说都足够了。
#include "Foo.h"
#include "MyVectorClass.h"
Foo foo;
...
auto result = foo.get();
阅读此代码时,我们很难找到为什么要包含MyVectorClass.h
。当Foo
的界面发生变化,get
开始返回AnotherVectorClass
或std::vector
时,我们应该删除每个获取用户中的旧MyVectorClass.h
方法,并包括一个适当的新标题。
这里的前瞻声明真的值得吗?
答案 0 :(得分:1)
我认为问题在于 。前向声明在编译速度方面提供了好处,但是以便利为代价。
一个例子是你给的那个。另一个原因是,甚至IDE和工具(例如VisualAssist)有时也不知道如何制作前向声明,并且无法跳转到实际类型。重构工具也是如此。
所以值得与否的问题取决于编译速度的提升是否值得。
如果你想给这个类的用户提供稍微好一点的提示,还有另外一个选择:你可以在“Foo.inl”文件中包含它的所有依赖项,用户需要包含它才能安全地使用它没有太多的麻烦,并且以更加面向未来的方式。
答案 1 :(得分:-1)
同样,Uncaught Error: [$injector:modulerr] Failed to instantiate module infographicsModule due to:
Error: [$injector:modulerr] Failed to instantiate module d3 due to:
Error: [$injector:nomod] Module 'd3' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
是静态类型的,并且不会帮助您获得所需的动态多态性。如果需要,可以使用迭代器或指针。
因此,这里的一个解决方案是从同一个基类继承所有auto
实现类,这样您每次更改内容时都不必担心编辑包含。
或者,您可以使用SomeVector
为您提供的数据,前提是get()
具有正确的迭代器,并且根本不使用中间MyVectorClass
类型。这对你的情况更好,因为你也可以使用stl向量本身。