The template application in C ++ programming language is a very important operation skill. Its Applications greatly improve the program development efficiency of programmers. In this article, we will focus on the application of C ++ template restrictions for your understanding.
1. floating point numbers cannot be used as non-type template parameters, such as: template <float/* or double */> class TT;
2. Custom classes cannot be used as template parameters. These custom classes are also non-type template parameters.
- // 6-14-2009
- #include <iostream>
- using namespace std;
- // #define FLOAT
- // #define TEMPLATE_OBJECT
- #define COMMON_OBJECT
- #ifdef FLOAT
- template <float f>
- class TT;
- #endif
- #ifdef TEMPLATE_OBJECT
- template < class T >
- class TM {};
- template < TM<int> c >
- class TT;
- #endif
- #ifdef COMMON_OBJECT
- class TN{};
- template < TN c >
- class TT;
- #endif
There is also a restriction on the C ++ template, and it is very important:
The declaration and definition of a template class or template function must be in the same file! Unless the next-generation compiler supports the keyword export.
If the compiler does not support the export keyword, but we want to separate the declaration from the definition, what should we do? The method is as follows:
Write the template declaration in. h, the template definition is written in. in cpp, it should be noted that we are not in. cpp contains. h, but in main. in cpp, include these two items as follows:
- // test.h
- template <typename T>
- class Test
- {
- public:
- void print();
- };
- // test.cpp
- template <typename T>
- void Test<T>::print()
- {
- cout << "Successfully!" << endl;
- }
- // main.cpp
- #include <iostream>
- using namespace std;
- #include "test.h"
- #include "test.cpp"
- int main()
- {
- Test<int> t;
- t.print();
- return 0;
- }
The preceding section describes the restrictions on the C ++ template.