C + + template separation

Source: Internet
Author: User

Under normal circumstances, C + + templates are not allowed in header file declarations, implemented in CPP files. That's because when the CPP file is compiled, the memory has to allocate storage space for it. But the template itself is generic, and the compiler cannot know its size until the claim type is explicitly defined. So there will be a link failure.

// print.h #ifndef _print_ #define _print_templatevoid  PRINT (T obj); #endif
 // print.cpp  #include  " print.h  "   <iostream>using    std;template  <typename t> void   print (T obj) {cout  <<obj;}  
// main.cpp#include"print.h"int  main () {    print (100 );      while (1);     return 0 ;}

If you do this, you will be prompted:

1>link:e:\mycode\ template \debug\ template detach. exe not found or not built by the last incremental LINK; performing full Link1"void __cdecl print<int> (int)" in function _main  11 unresolved externals

Common Solutions A total of 2 kinds:

1 is the definition also in the header file, this is needless to say. Since there is no need to define the compiler in the CPP file, it is not necessary to initially allocate memory, and there will be no error.

2 with an explicit instantiation declaration, as I said earlier, the template function defined in the CPP file cannot allocate memory because there is no deterministic type. At this time, just give a definite type, that is, an explicit instantiation of the declaration, just need to be in the header file with a certain type of declaration again.

// print.h #ifndef _print_ #define _print_templatevoidvoid print<int> (int ); #endif

This will pass through the compilation.

C + + template separation

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.