在不同的cpp文件中用同样类实例化某个模板函数那么是会产生多个函数的定义吗?
1.写两个.cpp文件和一个.h文件
test1.cpp
#include "test.h"
void func1()
{
func<int>(1);
}
int main()
{
return 0;
}
test2.cpp
#include "test.h"
void func2()
{
func<int>(2);
}
test.h
template<typename T>
int func(T t)
{
return t;
}
- g++ test1.cpp -c -o test1.o
- g++ test2.cpp -c -o test2.o
- g++ test1.o test2.o
- nm test1.o
- nm test2.o
- nm a.out
下面就看一下刚才屏幕上的输出吧
[root@VM_89_91_centos testCPP]# nm test1.o
0000000000000000 W _Z4funcIdEiT_ //有func<double>函数
0000000000000000 W _Z4funcIiEiT_ //有func<int>函数
0000000000000000 T _Z5func1v //有func1函数
U __gxx_personality_v0
000000000000001d T main //有main函数
[root@VM_89_91_centos testCPP]# nm test2.o
0000000000000000 W _Z4funcIcEiT_ //有func<char>函数
0000000000000000 W _Z4funcIiEiT_ //有func<int>函数
0000000000000000 T _Z5func2v //有func2函数
U __gxx_personality_v0
a.out中过滤了一些不重要的参数
[root@VM_89_91_centos testCPP]# nm a.out
00000000004005b6 W _Z4funcIcEiT_ //有func<char>函数
0000000000400588 W _Z4funcIdEiT_ //有func<double>函数
000000000040057c W _Z4funcIiEiT_ //有func<int>函数
0000000000400554 T _Z5func1v //有func1函数
000000000040059c T _Z5func2v //有func2函数
0000000000400571 T main
综上所述,不会产生多个模板函数的定义