0

Squads の動的配列を持つクラスがあるとしUnitます。#include「Unit.h」を「Squad.h」と後者のユーザーに使用しないようにする方法を探しています。#includeグローバルな考え方は、他のものにつながる sを避けることです - かなり厄介なことです。

次のような簡単な解決策を見つけました。

// Squad.h
class Unit;
class Squad {
private:
  Unit*  units;
  size_t units_num;
public:
  void do_something_with_units(); // its implementation requires Unit to be a full type
};
// Squad.cpp
#include "Unit.h" // it's fine (and required) in Squad.cpp
void Squad::do_something_with_units() { // implements
}
// squad_user.h
// I want this whole file to be satisfied with only
// a forward-declaration of Unit (coming from Squad.h)
// provided it doesn't interact with Unit directly
void foo() {
  Squad squad;
  squad.do_something_with_units(); // works!
}

(前方宣言されUnitた s をstd::vector内部に配置すると、のユーザーSquadが必要になるため失敗します。そうしないと、割り当てられません。)Squad#include Unitvector

質問その 1 : そのような慣行は容認されますか? std::vectorもちろん、 (およびその他の) の内臓を毎回書き直すつもりはありませんが、.cpptemplate<typename T> T* reallocate(T*, size_t current, size_t needed)で後の s のようなアルゴリズムを使用してヘッダーを作成することは耐えられるようです。#include

質問 2 : より良い解決策はありますか? pimpl の慣用句については知っていますが、頻繁に小さなヒープを割り当てるのは嫌いです。

ところで、std::unordered_map のようなより複雑なデータ構造が必要な場合、これをどうすればよいでしょうか? アレイの交換は難しくありませんが、このような「より悪い」ケースがあります。

4

1 に答える 1