I have a template class that has a big member function in generic form, so it is not very easy to read it through. I decide to move this function outside of the class body, and implement it in a ".cpp" file that with same name as the ".hpp", but I can't pass the compiling. If I implement it in a specialized form rather than a generic form, it can be compiled/linked, even though it be saved in the "*.cpp" file too.
The codes is following:
ClassC.hpp:
#pragma once
template <typename T>
class ClassC {
public:
ClassC( T* p ) : d( p ) {};
void show();
private:
T* d;
};
ClassC.cpp
#include <iostream>
#include "ClassC.hpp"
#include "ClassD.hpp"
using namespace std;
// this is a specialized version, and can be compiled/linked.
template <>
void ClassC<ClassD>::show() {
cout << "This is a specialized ClassC." << endl;
};
// this is my generic version, and can not be compiled.
template <typename T>
void ClassC::show() {
cout << "This is a generic ClassC." << endl;
};
/* */
ClassD.hpp
#pragma once
#include "ClassC.hpp"
class ClassD {
public:
ClassD(): c( this ) {};
void show();
private:
ClassC<ClassD> c;
};
ClassD.cpp
#include <iostream>
#include "ClassD.hpp"
using namespace std;
void ClassD::show() {
c.show();
cout << "This is ClassD" << endl;
};
main.cpp
#include "ClassD.hpp"
int main() {
ClassD d;
d.show();
return 0;
};