模板成员函数为什么不能是虚函数

模板成员函数不能是虚函数,因为这要求编译器在解析类时确定虚函数表的大小,而模板实例化可能导致在程序不同位置产生多个函数。这种做法对多文件项目不切实际。模板类实例化创建新类型,如Test<char>和Test<int>是不同类,不能直接相互赋值。通过模板拷贝构造函数可实现类型转换。同时,模板函数提供了一种特殊的重载方式,但不同于常规的重载机制,且无法用模板定义函数指针。
摘要由CSDN通过智能技术生成


《Thinking in C++》volume 2第五章有这么一句话:
Member template functions cannot be declared virtual.Current compiler technology experts to be able to determine the size of a class’s virtual function table when the class is parsed.Allowing virtual member template functions woule require knowing all calls to such member functions everywhere in the program ahead of time.This is not feasible,especially for multi-file projects.
在这段话里作者解释了为什么类的成员模板函数不能是虚函数。自己半懂不懂。没写过编译器,遇到费解的概念如编译时/运行时、静态/动态、内部连接/外部连接,以及很多比如“函数模板不能有默认的模板参数”这样的规则时,只好望洋兴叹。
然而问题不可累积。有必要借助这个问题明确一些基本的概念了。
首先:当模板类被实例化时,它实际上也产生了一种新的类型,不同的参数实例化出不同的类型。例如,用五个不同的参数分别实例化一个模板类,则相当于新定义了五个普通类。用代码说明问题:

  1. #include <iostream> 
  2. #include <typeinfo> 
  3. using namespace std; 
  4.   
  5. template <class Type> class Test { 
  6. public
  7.      void f() { 
  8.          cout << "My Type is: " << typeid(*this).name() << endl; 
  9.      } 
  10. }; 
  11.   
  12. int main() { 
  13.      Test<char>().f(); 
  14.      Test<int>().f(); 
  15.      
  16.      cout.setf(ios::boolalpha); 
  17.      
  18.      cout << bool(
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值