2017年完美世界一道笔试题

在不同的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;
}
  1. g++ test1.cpp -c -o test1.o
  2. g++ test2.cpp -c -o test2.o
  3. g++ test1.o test2.o
  4. nm test1.o
  5. nm test2.o
  6. 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

综上所述,不会产生多个模板函数的定义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值