How to optimize the template in Category 11
In this issue, Xiaobian will bring you about how to optimize the template in C++11. The article is rich in content and analyzed and described from a professional perspective. After reading this article, I hope you can gain something.
1. Right angle bracket of template
One of the most cumbersome aspects of template instantiation in generic programming is that two consecutive right angle brackets (>>) are resolved by the compiler to the right-shift operator, not to the end of the template parameter list. Let's first look at a piece of code about container traversal. In the created class template Base, we provide the operation function traversal():
// test.cpp#include #include using namespace std;template class Base{public: void traversal(T& t) { auto it = t.begin(); for (; it != t.end(); ++it) { cout) is parsed into template parameter terminators, which is convenient for us to write template-related code.
The above code is compiled without any problems in compilers that support C++11. If you use g++ to compile directly, you need to add the parameter-std=c++11.
2. Default template parameters
In the C++98/03 standard, class templates can have default template parameters:
#include using namespace std;template class Test{public: void print() { cout