template member function is instantiated only if called

你说的曾经没有我的故事 提交于 2021-01-19 04:44:18

问题


Why there is an error in this code:

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);
    }

My lecturer said there is an error in the c2.print(&d); line:

Compilation Error: Member function is instantiated only if called.

What does he mean?


回答1:


Member functions for class templates are only actually generated if they are used. This is an important part of templates which prevents unnecessary code bloat and allows support of types which don't fulfil the entire implicit contract for a template, but are sufficient for usage.

Your declarations of CLs<T> variables compile cleanly because the print function isn't compiled until it is used. c2.print(&d) fails to compile, because it causes the instantiation of CLs<double>::print, which is ill-formed.



来源:https://stackoverflow.com/questions/31157196/template-member-function-is-instantiated-only-if-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!