问题
The following code works fine:
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);
}
but the following extended version gives a linker error (unresolved external symbol) and I do more or less understand why. But how to fix it?
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);
}
I guess I need an analogue of the lines
template class Class<int>;
template std::ostream& operator<<(std::ostream& Stream, const Class<int>& Op);
for SubClass and also some sort of template version of
friend std::ostream& operator<<(std::ostream& Stream, const SubClass& Op);
but how to do it?
Edit: As this was claimed to be a duplicated of another question: My question here is very specific (see comments below) and is not answered by the quoted questions or even mentioned there.
回答1:
Just provide the definitions of the template functions in the .hpp files. I believe the following should work:
template <class T> class Class {
SubClass member;
public:
class SubClass {
public:
friend std::ostream& operator<<(std::ostream& Stream, const Class<T>& Op) {
return Stream;
}
};
}
来源:https://stackoverflow.com/questions/33986937/c-friends-in-template-classes-separation-of-interface-and-implementation