fti*_*sem 12 c++ template-specialization
我今天在这里提出第三个问题;-),但我对c ++模板编程和运算符重载都很陌生.
我正在尝试以下方法:
terminallog.hh
//snipped 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[]);
//snipped code
};
//snipped 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;
}
Terminallog &Terminallog::operator<<(const char v[]) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}
//snipped code
Run Code Online (Sandbox Code Playgroud)
尝试编译此代码,它给我一个链接器错误:
g++ src/terminallog.cc inc/terminallog.hh testmain.cpp -o test -Wall -Werror
/tmp/ccifyOpr.o: In function `Terminallog::operator<<(char const*)':
testmain.cpp:(.text+0x0): multiple definition of `Terminallog::operator<<(char const*)'
/tmp/cccnEZlA.o:terminallog.cc:(.text+0x0): first defined here
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
因此,我目前正在撞墙,寻找解决方案.但我在墙上找不到一个......
如果有人能告诉我我的错误,那就太好了
非常感谢
ftiaronsem
Pab*_*blo 13
这个功能
Terminallog &Terminallog::operator<<(const char v[]) {
std::cout << std::endl;
this->indent();
std::cout << v;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
不是模板,而是常规成员函数.如果这个.h文件包含在几个.cpp过滤器中,它将导致您看到的多重定义错误.如果您声明它inline,编译器将允许多个定义,并且您的错误应该被修复.
inline
Terminallog &Terminallog::operator<<(const char v[]) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5765 次 |
| 最近记录: |