官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 新闻| 仙游县| 桃园市| 天镇县| 满洲里市| 上饶市| 辽阳市| 巴林左旗| 图片| 宜川县| 元朗区| 察雅县| 咸宁市| 宁化县| 阿克苏市| 乌拉特后旗| 邳州市| 平罗县| 修文县| 西安市| 界首市| 蓝山县| 莒南县| 泸西县| 房山区| 丽水市| 吉林市| 黎川县| 阿拉善左旗| 宜昌市| 沁源县| 博野县| 本溪市| 屏边| 横山县| 乐至县| 大厂| 新龙县| 红原县| 进贤县| 桐乡市|