模板成员函数只有在被调用时才被实例化
template member function is instantiated only if called
为什么此代码中存在错误:
template <typename T>
class CLs{
public:
void print(T* p){ p->print(); }
};
void main() {
CLs<int> c1; // compilation OK
CLs<double> c2; // compilation OK
double d=3;
c2.print(&d);
}
我的讲师说c2.print(&d);
行有一个错误:
Compilation Error: Member function is instantiated only if called.
他是什么意思?
类模板的成员函数只有在使用时才实际生成。这是模板的一个重要部分,它可以防止不必要的代码膨胀,并允许支持那些不能满足模板的整个隐式约定,但足以使用的类型。
CLs<T>
变量的声明编译得很干净,因为print
函数在使用之前不会编译。c2.print(&d)
编译失败,因为它导致了CLs<double>::print
的实例化,这是不正确的。
相关文章:
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 对象实例化调用构造函数的次数太多
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 生成代码(在编译时)以调用模板的每个实例化的静态函数
- 实例化新类时未调用的方法
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 为什么C++可以使用派生结构来实例化其父模板结构,而父模板可以调用子结构的函数?
- 如何调用模板函数的每个实例化函数
- 如何在调用模板显式实例化时打开自动匹配
- 在不实例化的情况下调用不同派生类的虚拟方法
- 在不指定实例化的情况下调用类模板的静态方法的方法
- 是否可以在不实例化派生类的情况下调用该类的虚拟函数
- C 调用模板构造函数实例化
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法
- C++:从父实例化调用子方法
- 即使在内置素上实例化,也可以向模板参数类型的驱动器进行明确调用
- 正在成员调用中实例化类
- 为什么我可以在尚未实例化的类上调用函数
- 调用实例化函数时发生链接器错误