《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.
在这段话里作者解释了为什么类的成员模板函数不能是虚函数。自己半懂不懂。没写过编译器,遇到费解的概念如编译时/运行时、静态/动态、内部连接/外部连接,以及很多比如“函数模板不能有默认的模板参数”这样的规则时,只好望洋兴叹。
然而问题不可累积。有必要借助这个问题明确一些基本的概念了。
首先:当模板类被实例化时,它实际上也产生了一种新的类型,不同的参数实例化出不同的类型。例如,用五个不同的参数分别实例化一个模板类,则相当于新定义了五个普通类。用代码说明问题:
- #include <iostream>
- #include <typeinfo>
- using namespace std;
- template <class Type> class Test {
- public:
- void f() {
- cout << "My Type is: " << typeid(*this).name() << endl;
- }
- };
- int main() {
- Test<char>().f();
- Test<int>().f();
- cout.setf(ios::boolalpha);
- cout << bool(