when I add MYClass Specialization template , in this case, it will come out compile error, like this:
pet@iZbp1aq6c9kbbder4q405mZ:~/template_class/template_demo/2part/2_7$ g++ main.cpp test.cpp
/usr/bin/ld: /tmp/ccRiDoql.o: in function `MYClass<int>::func()':
test.cpp:(.text+0x0): multiple definition of `MYClass<int>::func()'; /tmp/ccvTW7yj.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
I can't find the reason. In this case, I add MYClass Specialization template, it also cause compile failed.I dont' know why. the details code is below like this: template.h
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
#include <iostream>
template <typename T>
class MYClass
{
public:
void func();
};
template <typename T>
void MYClass<T>::func()
{
std::cout << "MYClass::func!" << std::endl;
}
template <>
class MYClass<int>
{
public:
void func();
};
void MYClass<int>::func()
{
std::cout << "MYClass<int>::func!" << std::endl;
}
template <typename T>
void myfunc(T v1, T v2)
{
std::cout << v1 + v2 << std::endl;
}
#endif
test.cpp
#include <iostream>
#include "template.h"
using namespace std;
template class MYClass<float>;
template void myfunc(int v1, int v2);
void funcTest()
{
MYClass<float> a;
a.func();
}
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
extern template class MYClass<float>;
extern template void myfunc(int v1, int v2);
int main()
{
MYClass<float> mycls;
mycls.func();
myfunc<int>(1,2);
return 0;
}
I can't understand,why can't add this into here, when it removed, compile passed
template <>
class MYClass<int>
{
public:
void func();
};
void MYClass<int>::func()
{
std::cout << "MYClass<int>::func!" << std::endl;
}
Aucun commentaire:
Enregistrer un commentaire