C++ 模板与分离编译

1.分离编译模式

一个程序由若干个源文件共同实现,而每个源文件单独编译生成目标文件,最后将所有目标文件链接起来形成单一的可执行文件的过程称为分离编译模式。

2.使用函数模板在链接时正确编译(vs2019)

template_1.h

#pragma once

/* declare the template function */
template<class T> T add_(T, T);

template_2.cpp

#include"template_1.h"

template<class T> T add_(T a, T b)
{
	return a + b;
}

main.cpp

#include<stdio.h>
#include<string>
#include "template_1.h"

int main(int argc, char* argv[])
{

	int a = 10, b = 20;
	int c = add_<int>(a, b);

	std::string a("Hello ");
	std::string b("World!");

	std::string c = add_<std::string>(a, b);

	return 0;
}

3.模板类在编译时会有出现找不到符号的链接错误

template_1.h

template<class T> class A {
public:
	A()
	{

	}

	~A()
	{

	}

	T add(T a, T b);

private:
};

template_1.cpp

#include"template_1.h"


template<class T>
T A<T>::add(T a, T b)
{
	return a + b;
}

 main.cpp

#include<stdio.h>
#include<string>
#include "template_1.h"

int main(int argc, char* argv[])
{
	std::string d("Hello ");
	std::string e("World!");

	A<int> m_a;
	int g = m_a.add(10, 30);

	A<std::string> m_a_1;
	std::string h = m_a_1.add(d, e);

	return 0;
}

编译会出现如下的错误: 

怎么解决这个问题呢? 

方法一:将类申明和定义都放到头文件中;

方法二:模板显式实例化:

template_1.h

template<class T> class A {
public:
	A()
	{

	}

	~A()
	{

	}

	T add(T a, T b);

private:
};

template_1.cpp

#include"template_1.h"

template<class T> T add_(T a, T b)
{
	return a + b;
}

//template<class T>
//T A<T>::add(T a, T b)
//{
//
//	return a + b;
//}

template<>
int A<int>::add(int a, int b)
{
	return a + b;
}

template<>
std::string A<std::string>::add(std::string a, std::string b)
{
	return a + b;
}

main.cpp

#include<stdio.h>
#include<string>
#include "template_1.h"

int main(int argc, char* argv[])
{
	std::string d("Hello ");
	std::string e("World!");

	A<int> m_a;
	int g = m_a.add(10, 30);

	A<std::string> m_a_1;
	std::string h = m_a_1.add(d, e);

	return 0;
}

这两种方法都是可以编译通过的,当然目前行之有效的方法也就是这两种了!可以自行编写练习加深体会,至于模板是如何编译的可参考前面的几篇文章。

发布了140 篇原创文章 · 获赞 65 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/paradox_1_0/article/details/103585362
今日推荐