debug
オブジェクトに関する情報を出力する関数を作成したいと考えています。私のシステムには、さまざまな種類のオブジェクトが含まれています。それらのいくつかには、他のオブジェクトが含まれています。
using namespace std; // for brevity
struct dog {string name;};
struct human {string name; string address;};
struct line {list<human*> contents;};
struct pack {vector<dog*> contents;};
関数に引数のメンバーがある場合はそのメンバーを出力するname
か、引数のメンバーがある場合はそれをデバッグするcontents
ようにします。次のコードを思いつきました:
template <class T>
void debug(T object) // T here is a simple object like dog, human, etc
{
cout << object.name.c_str() << '\n';
}
// A helper function, not really important
template <class T>
void debug_pointer(T* object)
{
debug(*object);
}
void debug(pack object)
{
for_each(object.contents.begin(), object.contents.end(), debug_pointer<dog>);
}
void debug(line object)
{
for_each(object.contents.begin(), object.contents.end(), debug_pointer<human>);
}
pack
ここで、とのコードline
はほぼ同じです! 同じコードを何度も書くのは避けたい:
struct line {list<human*> contents; typedef human type;};
struct pack {vector<dog*> contents; typedef dog type;};
template <class T>
void debug(T object) // T here is a compound object (having contents)
{
for_each(object.contents.begin(), object.contents.end(), debug_pointer<T::type>);
}
ただし、この構文は、「単純な」オブジェクト (同じ署名を持つ) の関数テンプレートと競合します。
コードを書き直すにはどうすればよいですか? 私のプログラムのその部分はすでに非常に複雑であり、デバッグのためだけに何か(基本クラス、メンバー関数など)を追加するのは場違いに思えますdog
。human