- Expert C++
- Vardan Grigoryan Shunguang Wu
- 244字
- 2021-06-24 16:34:07
Syntax
If a function or class template takes zero or more parameters, it can be defined as follows:
//a class template with zero or more type parameters
template <typename... Args> class X { ... };
//a function template with zero or more type parameters
template <typename... Args> void foo( function param list) { ...}
Here, <typename ... Args> declares a parameter pack. Note that here, Args is not a keyword; you can use any valid variable names. The preceding class/function template can take any number of typename as its arguments need to be instantiated, as shown here:
X<> x0; //with 0 template type argument
X<int, std::vector<int> > x1; //with 2 template type arguments
//with 4 template type arguments
X<int, std::vector<int>, std::map<std::string, std::vector<int>>> x2;
//with 2 template type arguments
foo<float, double>( function argument list );
//with 3 template type arguments
foo<float, double, std::vector<int>>( function argument list );
If a variadic template needs at least one type parameter, then the following definition is used:
template <typename A, typename... Rest> class Y { ... };
template <typename A, typename... Rest>
void goo( const int a, const float b) { ....};
Similarly, we can instantiate them by using the following code:
Y<int > y1;
Y<int, std::vector<int>, std::map<std::string, std::vector<int>>> y2;
goo<int, float>( const int a, const float b );
goo<int,float, double, std::vector<int>>( const int a, const float b );
In the preceding code, we created the y1 and y2 objects from the instantiations of the variadic class template, Y, with one and three template arguments, respectively. For the variadic function goo template, we instantiate it as two template functions with two and three template arguments, respectively.
- iOS 9 Game Development Essentials
- Python網絡爬蟲從入門到實踐(第2版)
- CouchDB and PHP Web Development Beginner’s Guide
- 基于Swift語言的iOS App 商業實戰教程
- 3D少兒游戲編程(原書第2版)
- Nginx實戰:基于Lua語言的配置、開發與架構詳解
- Java程序設計入門
- Node.js:來一打 C++ 擴展
- Django實戰:Python Web典型模塊與項目開發
- Android嵌入式系統程序開發:基于Cortex-A8(第2版)
- 貫通Tomcat開發
- Java程序設計實用教程(第2版)
- HTML5 WebSocket權威指南
- 跟小樓老師學用Axure RP 9:玩轉產品原型設計
- 面向物聯網的Android應用開發與實踐