成员函数模板,显示实例化与声明

一:普通类的成员函数模板

#include "pch.h"
#include <iostream>
using namespace std;

class B
{
public:
	int a;
public:
	template<typename U>
	void fun(U obj)
	{
		cout<<"void fun(U obj)"<<endl;
		cout << obj << endl;
	}

	template<typename U>
	void func(U obj);
};

template<typename U>
void B::func(U obj)
{
	cout << "void B::func(U obj)" << endl;
	cout << obj << endl;
}


int main()
{
	B b;
	cout << sizeof(b) << endl;

	b.fun(1);
	b.func(2);

	return 0;
}

/*
总结一下:
1:在一个普通类里,也可以把成员函数定义成函数模板
2:注意上面的类外定义的写法
*/

二:类模板的成员函数模板

#include "pch.h"
#include <iostream>
using namespace std;

template<typename C>
class B
{
public:
	int a;
public:
	template<typename U>
	void fun(U obj)
	{
		cout<<"void fun(U obj)"<<endl;
		cout << obj << endl;
	}

	template<typename U>
	void func(U obj);
};

template<typename C>
template<typename U>
void B<C>::func(U obj)
{
	cout << "void B::func(U obj)" << endl;
	cout << obj << endl;
}


int main()
{
	B<int> b;
	cout << sizeof(b) << endl;

	b.fun<int>(1);//显示指定函数模板的类型,也可自动推导
	b.func<float>(2);//显示指定函数模板的类型,也可自动推导,这里以<为准>

	return 0;
}

/*
总结一下:
1:在一个类模板里,也可以把成员函数定义成函数模板
2:注意上面的成员函数模板类外定义的写法
*/

在这里插入图片描述
总结:
1:类模板的成员函数,只有源程序当中出现了调用这些成员函数的代码时,这些成员函数才会出现在一个实例化了的类模板中。
2:类模板中的成员函数模板,只有源程序当中出现调用了这些成员函数模板的代码时,这些成员函数模板的具体实例才会出现在一个已经实例化了的类模板当中。

三:模板显示实例化与声明

#include "pch.h"
#include "test.h"
#include <iostream>
using namespace std;
extern template B<int>;
int main()
{
	B<int> b; //实例化出一个B<int>类
	b.fun(2);
	return 0;
}


/*
1:在main.cpp和test.cpp当中都有B<int>代码
当编译器遇到这种代码时,都会在这个cpp文件当中,
实例化出这样一个版本的类,如果cpp文件很多的话,
就会在每个cpp文件当中都生成这样的实例化代码,
所以,为了减少系统开销,就有了显示实例化定义和声明。

extern template B<int>;
template B<int>;

定义只有一次,而声明可以有多次。

使用了显示实例化声明,到底有没有减少系统开销取决于编译器。

*/
#ifndef _TEST_H
#define _TEST_H


#include "pch.h"
#include <iostream>
using namespace std;

template<typename T>
class B
{
public:
	int a;
public:
	void fun(T obj)
	{
		cout << "void fun(T obj)" << endl;
		cout << obj << endl;
	}
};


#endif // !_TEST_H
#include "pch.h"
#include "test.h"

template B<int>;
void func()
{
	B<int> b; //实例化出一个B<int>类
	b.fun(1);
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值