【发布时间】:2012-01-29 15:30:21
【问题描述】:
我想创建一个名为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 等的声明),因为我的程序的那部分已经非常复杂,并且添加东西(基类、成员函数等)只是为了调试似乎不合适。
【问题讨论】:
标签: c++ templates template-specialization one-definition-rule