私は前方宣言をよく使用しました。それらは多く#include
のを回避し、コンパイル時間を改善するのに役立ちます。しかし、標準ライブラリでクラスを前方宣言したい場合はどうなりますか?
// Prototype of my function - i don't want to include <vector> to declare it!
int DoStuff(const std::vector<int>& thingies);
前方宣言は禁止/不可能だと聞きましたstd::vector
。さて、無関係な質問に対するこの答えは、私のコードを次のように書き直すことを示唆しています。
stuff.h
class VectorOfNumbers; // this class acts like std::vector<int>
int DoStuff(const VectorOfNumbers& thingies);
stuff.cpp
// Implementation, in some other file
#include <vector>
class VectorOfNumbers: public std::vector<int>
{
// Define the constructors - annoying in C++03, easy in C++11
};
int DoStuff(const VectorOfNumbers& thingies)
{
...
}
VectorOfNumbers
これで、プロジェクト全体ですべてのコンテキストの代わりに使用するとstd::vector<int>
、すべてがうまくいくようになり#include <vector>
、ヘッダーファイルに含める必要がなくなります。
この手法には大きな欠点がありますか?前方宣言ができることの利益は、vector
それらを上回ることができますか?