问题
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