还有另一个我无法解决的模板专业化问题:
终端日志.hh
//stripped code
class Terminallog {
public:
Terminallog();
Terminallog(int);
virtual ~Terminallog();
template <class T>
Terminallog & operator<<(const T &v);
template <class T>
Terminallog & operator<<(const std::vector<T> &v);
template <class T>
Terminallog & operator<<(const T v[]);
Terminallog & operator<<(const char v[]);
//stripped code
};
terminallog.hh 继续(编辑感谢评论)
//stripped code
template <class T>
Terminallog &Terminallog::operator<<(const T &v) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}
template <class T>
Terminallog &Terminallog::operator<<(const std::vector<T> &v) {
for (unsigned int i = 0; i < v.size(); i++) {
std::cout << std::endl;
this->indent();
std::cout << "Element " << i << ": " << v.at(i);
}
return *this;
}
template <class T>
Terminallog &Terminallog::operator<<(const T v[]) {
unsigned int elements = sizeof (v) / sizeof (v[0]);
for (unsigned int i = 0; i < elements; i++) {
std::cout << std::endl;
this->indent();
std::cout << "Element " << i << ": " << v[i];
}
return *this;
}
inline
Terminallog &Terminallog::operator<<(const char v[]) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}
//stripped code
这编译得很好,没有错误。但是,当我尝试执行以下操作时:
Terminallog clog(3);
int test[] = {5,6,7,8};
clog << test;
它总是向我打印数组的指针地址。换句话说,专门的模板
Terminallog & operator<<(const T v[]);
永远不会被调用。我还通过额外的 cout 验证了这一点。无论我尝试什么,程序总是在调用
Terminallog & operator<<(const T &v);
而不是专业。显然我的代码中必须有一个错误,但是我找不到它。