zl程序教程

您现在的位置是:首页 >  其他

当前栏目

模板形参包的展开方法

模板方法 展开
2023-09-14 09:07:07 时间

到底啥是形参包展开,我们先看看语法,如下:

模式 ...

在模式后面加省略号,就是包展开了,而所谓的模式一般都是形参包名称或者形参包的引用,包展开以后就变成零个或者多个逗号分隔的实参。

比如上面的age …和Fargs…都属于包展开,但是要知道,这种形式我们是没有办法直接使用的,那么具体该怎么使用呢,有两种办法:

  • 一是使用递归的办法把形参包里面的参数一个一个的拿出来进行处理,最后以一个默认的函数或者特化模板类来结束递归;
  • 二是直接把整个形参包展开以后传递给某个适合的函数或者类型。

递归方法适用场景:多个不同类型和数量的参数有比较相似的动作的时候,比较适合使用递归的办法。

关于整个形参包传递的使用方法,看下面代码:

#include <iostream>
#include <string>
using namespace std;

class programmer
{
    string name;
    string sex;
    int age;
    string vocation;//职业
    double height;
public:
    programmer(string name, string sex, int age, string vocation, double height)
    :name(name), sex(sex), age(age), vocation(vocation), height(height)
    {
        cout << "call programmer" << endl;
    }
    
    void print()
    {
        cout << "name:" << name << endl;
        cout << "sex:" << sex << endl;
        cout << "age:" << age << endl;
        cout << "vocation:" << vocation << endl;
        cout << "height:" << height << endl;
        
    }
};

template<typename T>
class xprintf
{
    T * t;
public:
    xprintf()
    :t(nullptr)
    {}
    
    template<typename ... Args>
    void alloc(Args ... args)
    {
        t = new T(args...);
    }
    
    void print()
    {
        t->print();
    }
    
    void afree()
    {
        if ( t != nullptr )
        {
            delete t;
            t = nullptr;
        }
    }
};
 
int main()
{
    xprintf<programmer> xp;
    xp.alloc("小明", "男", 35, "程序员", 169.5);
    xp.print();
    xp.afree();
    return 0;
}

这里类型xprintf是一个通用接口,类模板中类型T是一个未知类型,我们不知道它的构造需要哪些类型、多少个参数,所以这里就可以在它的成员函数中使用变参数模板,来直接把整个形参包传递给构造函数,具体需要哪些实参就根据模板类型T的实参类型来决定。