博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++11——variadic template
阅读量:277 次
发布时间:2019-03-01

本文共 2412 字,大约阅读时间需要 8 分钟。

例1:

//例1:void print()//递归出口{
cout << "递归出口" << endl;}template
//版本1void print(const T&firstArg, const Types&...args){
cout << firstArg << endl; print(args...);}template
//版本2void print(const Types&...args){
cout << "test" << endl; print(args...);}//注意:版本1比版本2更特化,所以版本2永远不会被调用int main(){
print(7.5, "hello", bitset<16>(377), 42); system("pause"); return 0;}

在这里插入图片描述

例2:简单实现形参为initializer_list的max函数

//例2template
_ForwardIterator_my_max_element(_ForwardIterator _first, _ForwardIterator _last,_Compare cmp){
if (_first == _last)return _first; _ForwardIterator _result = _first; while (++_first != _last) {
if (cmp(_result, _first)) _result = _first; } return _result;}//自定义比较函数functorclass cmp{
public: template
bool operator()(_Iterator1 _it1, _Iterator2 _it2)const {
return *_it1 < *_it2; }};template
inline _ForwardIteratormy_max_element(_ForwardIterator _first, _ForwardIterator _last){
return _my_max_element(_first, _last, cmp());}template
inline _T my_max(initializer_list<_T>_l){
return *my_max_element(_l.begin(), _l.end());}int main(){
cout << my_max({
1,2,5,3,7,9,5 }) << endl; cout << max({
1,2,5,3,7,9,5 }) << endl;//这是标准库中的版本 system("pause"); return 0;}

例3:利用可变参数模板实现例2的效果

int maximum(int n)//只有1个参数时调用这个版本,是递归的出口{
return n;}template
int maximum(int n, Args... args)//至少2个参数才可以调用这个版本{
return max(n, maximum(args...));}int main(){
cout << maximum(1, 2, 5, 3, 7, 9, 5) << endl; system("pause"); return 0;}

例4:使用可变参数模板简单实现tuple

在这里插入图片描述

对于上图的代码,要改一个错误的地方,见下图的黄标处。
在这里插入图片描述
这张图看明白后发现真的是经典!

#include
#include
#include
#include
#include
using namespace std;template
class my_tuple;//版本1template<>class my_tuple<> { };//版本1对应的全特化,作为递归的出口template
//比版本1更特化的版本2class my_tuple
:private my_tuple
{ public: //default constructor my_tuple() { } //constructor my_tuple(Head v, Tail... vtail) :m_head(v), my_tuple
(vtail...) { }//初始化列表中调用了基类的constructor Head head() { return m_head; } my_tuple
& tail() { return *this; }//返回的是直接基类的对象(派生类对象赋给一个基类引用)protected: Head m_head;};int main(){ my_tuple
t(41, 6.3, "nico"); cout << t.head() << endl;//41 cout << t.tail().head() << endl;//6.3 cout << t.tail().tail().head() << endl;//nico system("pause"); return 0;}

在这里插入图片描述

当然,上面这个例子是利用了继承的方式创建,其实也可以用嵌套(复合)的方式:
在这里插入图片描述

转载地址:http://zamt.baihongyu.com/

你可能感兴趣的文章