Hi,
For a while I have had some problem understanding just how template
specialisation works in certain cases. In abridged form my code looks
like this;
--MyTemplate.h--
#ifndef MyTemplateH
#define MyTemplateH
template <class Type>
class MyTemplate
{
public:
void MyMethod(void);
};
#include "MyTemplate.inl"
#endif
--MyTemplate.inl--
#include <iostream>
#include <string>
template <class Type>
void MyTemplate<Type>::MyMethod(void)
{
std::cout << "MyTemplate<Type>::MyMethod" << std::endl;
}
template<>
void
MyTemplate<bool>::MyMethod
(void)
{
std::cout << "MyTemplate<bool>::MyMethod" << std::endl;
}
--main.cpp--
#include <iostream>
#include "MyTemplate.h"
//#include "MyClass.h"
using namespace std;
int main(void)
{
cout << "Template Specialisation Test" << endl;
MyTemplate<double> myDoubleTemplate;
MyTemplate<bool> myBoolTemplate;
myDoubleTemplate.MyMethod();
myBoolTemplate.MyMethod();
//MyClass myClass;
//myClass.MyOtherMethod();
}
If I compile and run this (gcc on cygwin);
g++ main.cpp
../a
I get exactly what I expect:
Template Specialisation Test
MyTemplate<Type>::MyMethod
MyTemplate<bool>::MyMethod
However, if I uncomment the MyClass stuff and compile in the relevant
files;
--MyClass.h--
#ifndef MyClassH
#define MyClassH
class MyClass
{
public:
void MyOtherMethod(void);
};
#endif
--MyClass.cpp--
#include "MyClass.h"
#include "MyTemplate.h"
#include <iostream>
void MyClass::MyOtherMethod(void)
{
std::cout << "MyClass::MyOtherMethod" << std::endl;
MyTemplate<double> myClassDoubleTemplate;
myClassDoubleTemplate.MyMethod();
MyTemplate<bool> myClassBoolTemplate;
myClassBoolTemplate.MyMethod();
}
I get this;
$ g++ main.cpp MyClass.cpp
/cygdrive/c/DOCUME~1/sjs1/LOCALS~1/Temp/cc4Op3z4.o(.text+0x0):MyClass.cpp:
multi
ple definition of `MyTemplate<bool>::MyMethod()'
/cygdrive/c/DOCUME~1/sjs1/LOCALS~1/Temp/ccPG3TEU.o(.text+0x0):main.cpp:
first de
fined here
collect2: ld returned 1 exit status
Now, I can understand this, given that the .inl file is included in
both places - but I have tried moving stuff the specialisation or the
template method or both into seperate .cpp files, with absolutely no
success; any ideas how to resolve this?
Stephen.