以下代码可以正常使用:
Class.h:
#ifndef ClassLoaded
#define ClassLoaded
#include <iostream>
template <class T> class Class{
public:
template <class T> friend std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op);
};
#endif
Class.cpp:
#include "Class.h"
template class Class<int>;
template std::ostream& operator<<(std::ostream& Stream, const Class<int>& Op);
template <class T> std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op){
return(Stream);
}
Main.cpp的:
#include "Class.h"
#include <iostream>
using namespace std;
int main(){
Class<int> Test;
cout << Test << endl;
return(0);
}
但是以下扩展版本给出了链接器错误(未解析的外部符号),我或多或少地理解了原因。但是如何解决呢?
Class.h:
#ifndef ClassLoaded
#define ClassLoaded
#include <iostream>
template <class T> class Class{
public:
class SubClass{
public:
friend std::ostream& operator<<(std::ostream& Stream, const SubClass& Op);
};
template <class T> friend std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op);
private:
SubClass Member;
};
#endif
Class.cpp:
#include "Class.h"
template class Class<int>;
template std::ostream& operator<<(std::ostream& Stream, const Class<int>& Op);
template <class T> std::ostream& operator<<(std::ostream& Stream, const typename Class<T>::SubClass& Op){
return(Stream);
}
template <class T> std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op){
Stream << Op.Member;
return(Stream);
}
Main.cpp的:
#include "Class.h"
#include <iostream>
using namespace std;
int main(){
Class<int> Test;
cout << Test << endl;
return(0);
}
我想我需要一个类似的线
template class Class<int>;
template std::ostream& operator<<(std::ostream& Stream, const Class<int>& Op);
用于SubClass以及某种
的模板版本friend std::ostream& operator<<(std::ostream& Stream, const SubClass& Op);
但该怎么做?
编辑:因为这被认为是另一个问题的重复:我的问题非常具体(见下面的评论),并没有被引用的问题回答,甚至没有在那里提到。
答案 0 :(得分:0)
只需在.hpp文件中提供模板函数的定义即可。 我相信以下内容应该有效:
template <class T> class Class {
SubClass member;
public:
class SubClass {
public:
friend std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op) {
return Stream;
}
};
}