最近使用了c++模板,觉得非常强大,只是写起来需要掌握一点技巧。大部分模板都是直接把定义写在.h头文件,并且有些人还说这样做的原因是模板不支持分编译,可是以前的编译器对模板的支持不够好吧,但是现在完全可以。

环境:

win7 32旗舰版、VS2010 sp1

1、普通函数模板

define.h文件

template<typename T>
T GetString(int value);
define.cpp文件

2、类模板

define.h文件

template<typename T>
class A
{
public:
	A()
	{
		InitValue();
	}

	void InitValue();

	int m_nValue;
};

define.cpp文件 

template<typename T>
A<T>::A()
{
	InitValue();
}

template<>
void A<string>::InitValue()
{
	m_nValue = 100;
}

template<>
void A<int>::InitValue()
{
	m_nValue = 200;
}

// 类模板实例化
template
A<int>;

3、成员函数模板

define.h文件

class B
{
public:
	template<typename T>
	T Get(int index);
};

define.cpp文件

//成员函数模板偏特化
template<>
double B::Get<double>(int index)
{
	return 2.1;
}

//成员函数模板偏特化
template<>
int B::Get<int><int>(int index)
{
	return 1;
}
</int>

//如果类B是一个数据库封装类,我们就可以利用这样的调用方式来获取数据库一条记录中的字段

B b;
b.Get<int>(1);//获取当前记录中第一个字段的值,并转化为int类型
b.Get<double>(2)//获取当前记录中第二个字段的值,并转化为double类型

这样是不是非常方便^^。

相关文章:

  • 2022-12-23
  • 2021-05-30
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2021-05-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-11
  • 2021-07-09
  • 2022-12-23
  • 2021-11-25
  • 2022-01-04
  • 2021-08-04
相关资源
相似解决方案