模板成员函数只有在被调用时才被实例化

template member function is instantiated only if called

本文关键字:调用 实例化 成员 函数      更新时间:2023-10-16

为什么此代码中存在错误:

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的实例化,这是不正确的。