【问题标题】:template member function is instantiated only if called模板成员函数仅在调用时被实例化
【发布时间】:2015-07-01 09:13:33
【问题描述】:

为什么这段代码有错误:

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(&amp;d); 行有错误:

Compilation Error: Member function is instantiated only if called.

他是什么意思?

【问题讨论】:

  • 变量 ddouble 类型,所以当你在函数体中调用 c2.print(&amp;d) 就像调用 d.print() 但 d 是一个具体类型并且没有成员函数print.

标签: c++ templates member-functions


【解决方案1】:

类模板的成员函数只有在使用时才会实际生成。这是模板的一个重要部分,它可以防止不必要的代码膨胀,并允许支持不满足模板的整个隐式契约但足以使用的类型。

CLs&lt;T&gt; 变量的声明编译干净,因为 print 函数在使用之前不会编译。 c2.print(&amp;d) 无法编译,因为它会导致 CLs&lt;double&gt;::print 的实例化,这是格式错误的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多