Why the C + + class template declaration and definition cannot be separated

Source: Internet
Author: User

The amount of space occupied by each object in C + + is determined at compile time, and before the template class is actually used, the compiler is unable to know the size of the space occupied by the object using the template type in the template class. Only when the template is actually used does the compiler know what type of template to apply and how much space should be allocated. This is why the template class is simply called a template, not a generic type.

Since it is compiled at compile time, according to the different types of the compilation, then, to apply the different types of template class is actually two different types, that is,,stack<int> and stack<char> are two different data types, Their common member functions are not the same function, but they have similar functions.

As shown, a very short six lines of code, with the STL inside the default constructor of Stack,stack<int> and Stack<char> and the import address of the push function is not the same, and the different stack<int> The same function entry address is the same as the object, this also reflects the template class after applying different types, will be compiled by different code phenomenon.

Therefore, the implementation of the template class, separated from the specific use, can not be compiled separately; the separation of declarations and implementations is also undesirable, and the implementation must be written in the header file. To be clear, the implementation can be written outside the curly braces that are behind the class.

Reprint of self-knowledge over the days L

Why the C + + class template declaration and definition cannot be separated

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.