template member function is instantiated only if called

前端 未结 1 849
谎友^
谎友^ 2021-01-14 02:57

Why there is an error in this code:

template 
    class CLs{
        public:
        void print(T* p){ p->print(); }
    };

    void ma         


        
相关标签:
1条回答
  • 2021-01-14 03:32

    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.

    0 讨论(0)
提交回复
热议问题