Quote from the C++primer (Fourth edition) View:
1 Standard C + + defines two models for compiling the template code: the Include model and the "compile separately" model.
2 All compilers support the "include" model, and some compilers support the "compile separately" model.
Question: (Post in: http://topic.csdn.net/u/20101215/15/f4f270f2-f0f9-4c5f-8765-1bfde2aeebbf.html) method One:
Both the declaration and the implementation are placed in the header file.
In the class template header file Template_compile.h:
Template<class t>
class base
{public
:
base () {};
~base () {};
T Add_base (t x,t y);
};
Template<class t>
t base<t>::add_base (t x,t y)
{return
x+y;
In the test file use_template.cpp using the template:
#include <iostream>
#include "template_compile.h"
using namespace std;
void Main ()
{
base<int> bobj;
Cout<<bobj.add_base (2,3) <<endl;
}
Method Two:
Press the "include" model in C++primer to define the last line in the header file of the template class: #include "Template_compile.cpp"
In the class template header file Template_compile.h:
Template<class t>
class base
{public
:
base () {};
~base () {};
T Add_base (t x,t y);
};
#include "Template_compile.cpp"
In the implementation file Template_compile.cpp of the class template:
Template<class t>
t base<t>::add_base (t x,t y)
{return
x+y;
The test file does not change. Method Three
Using define
In the class template header file Template_compile.h:
Template<class t>
class base
{public
:
base () {};
~base () {};
T Add_base (t x,t y);
};
#define TEMP
#include "template_compile.cpp"
In the implementation file Template_compile.cpp of the class template:
#ifdef TEMP
template<class t>
t base<t>::add_base (t x,t y)
{return
x+y;
}
#endif
The test file does not change. method Four
In the class template header file Template_compile.h:
Template<class t>
class base
{public
:
base () {};
~base () {};
T Add_base (t x,t y);
};
In the implementation file Template_compile.cpp of the class template:
#include "template_compile.h"
template<class t>
t base<t>::add_base (t x,t y)
{
return x+y;
}
In the test file use_template.cpp using the template: Use #include "template_compile.cpp"
#include <iostream>
#include "template_compile.cpp"
using namespace std;
void Main ()
{
base<int> bobj;
Cout<<bobj.add_base (2,3) <<endl;
}