c++模板类的基础问题

zhfkt 2014-01-11 09:01:46
有下列代码,可以在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()函数的定义都是相同的,但是特化模板会特化整个的类。现在想其它函数可以公用,不用重复定义,应该如何实现。







...全文
167 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
AndyStevens 2014-01-13
  • 打赏
  • 举报
回复
1. 考虑到模板特化的定义,如果都采用mytest:: 可能会引起冲突. 2. 全局特化和普通函数/类是类似的,不应再看为模板,如果定义出现在头文件中会出现重定义。 3. 可以使用全局成员特化:
template<>
void mytest<yourtype>::method(yourtype input){};
vipcxj 2014-01-12
  • 打赏
  • 举报
回复
C++语法就是那么规定滴,你能怎么着?
derekrose 2014-01-11
  • 打赏
  • 举报
回复
意思清楚不清楚不是写给人看的,是写给编译器看的
taodm 2014-01-11
  • 打赏
  • 举报
回复
那个,模板的基础语法你欠缺太多了点,还是找本教材吧。 并且,你需要《execptional c++》系列

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧