C++ 模板类与头文件

今天将模板类函数分成了声明和定义两个文件:

模板类的声明:

#pragma once

#ifndef FIND_ITEM
#define FIND_TIEM
template <typename elemType>
const elemType* find_item(const elemType* first,
	const elemType* last, const elemType& value);

void print_hello();

#endif

模板类的定义 

#include "iostream"
void print_hello()
{
	std::cout << "what the fuck"<<std::endl;
}
{
	if (!first || !last)
		return 0;
	for (; first != last; ++first)
		if (*first == value)
			return first;
	return 0;

}
template <typename elemType>
const elemType* find_item(const elemType* first,
	const elemType* last, const elemType& value)
{
	if (!first || !last)
		return 0;
	for (; first != last; ++first)
		if (*first == value)
			return first;
	return 0;

}

main函数:

#include <iostream>
#include <vector>
#include "find.hh"
using namespace std;


int main()
{
	int a[] = {98,12,33,41,58,976,11,0,44};
	vector<int> vec_a(a, a + 7);

	const int* vec_index;

	vec_index = find_item(a,a+7, a[4]);


	print_hello();
    std::cout << "Hello World!\n"<<(vec_index - a);
}

单独编译定义的文件是可以通过的,但是整体编译在一起就死活不行了。

定位问题是,模板类只能是现在头文件中,是因为编译顺序决定的。

如果是普通类型函数的声明,在main中使用的时候,是需要留出函数的接口,在链接时链接就好了。

但是模板类,如果在链接的时候链接,会发现,main函数里所使用的的函数是具体的类型,但是模板定义的里面是template,链不上。所以应当将模板类的定义放到头文件中,编译器开始编译的时候就已经知道了函数的模板,在编译各个应用了模板函数的时候,直接替换掉就好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值