c++模板类的基础问题
有下列代码,可以在vs2013中编译通过
//template_test.h
#include <iostream>
using namespace std;
template<class T>
class mytest
{
public:
void method(T input);
void common();
};
template <>
class mytest<char>
{
public:
void method(char input);
void common();
};
template<class T>
void mytest<T>::method(T input)
{
cout << input << endl;
}
template<class T>
void mytest<T>::common()
{
cout << "common" << endl;
}
//template_test.cpp
#include "template_test.h"
void mytest<char>::method(char input)
{
cout << "char:" << input << endl;
}
void mytest<char>::common()
{
cout << "common" << endl;
}
//main.cpp
#include "template_test.h"
using namespace std;
int main()
{
mytest<char> test_char;
test_char.method('1');
test_char.common();
mytest<int> test_int;
test_int.method(1);
test_int.common();
system("pause");
return 0;
}
1.
在实现 类模板定义的那一行,即
template<class T>
void mytest<T>::method(T input)
{
cout << input << endl;
}
为何不是
template<class T>
void mytest::method(T input)
{
cout << input << endl;
}
去掉第二个T后,意思也非常清楚,为什么还要加上那个T,第二个T的作用是什么
2.可以看到.h文件中有一个对于mytest类的特化模板
template <>
class mytest<char>
{
public:
void method(char input);
void common();
};
而它的实现是在cpp中实现的
//template_test.cpp
#include "template_test.h"
void mytest<char>::method(char input)
{
cout << "char:" << input << endl;
}
void mytest<char>::common()
{
cout << "common" << endl;
}
如果模板类的声明在.h中,实现在.cpp中,那么就会报错,c++不能对于模板进行木板上的的分离式编译
但是,对于特化模板来说,如果将上述定义扔到.h中,反而会报错,只能放到cpp中,这个又是为什么
3.可以看到对于原始模板类和特化模板类来说
template<class T>
class mytest
{
public:
void method(T input);
void common();
};
template <>
class mytest<char>
{
public:
void method(char input);
void common();
};
我想要特化的只是其中的一个函数,而common()函数的定义都是相同的,但是特化模板会特化整个的类。现在想其它函数可以公用,不用重复定义,应该如何实现。
[解决办法]
1. 考虑到模板特化的定义,如果都采用mytest:: 可能会引起冲突.
2. 全局特化和普通函数/类是类似的,不应再看为模板,如果定义出现在头文件中会出现重定义。
3. 可以使用全局成员特化:
template<>
void mytest<yourtype>::method(yourtype input){};