zoukankan      html  css  js  c++  java
  • c++11 可变参数模板类

    c++11 可变参数模板类

    #define _CRT_SECURE_NO_WARNINGS
    
    #include <iostream>
    #include <string>
    #include <vector>
    #include <map>
    
    // 在C++11之前,类模板和函数模板只能含有固定数量的模板参数。C++11增强了模板功能,允许模板定义中包含0到任意个模板参数,这就是可变参数模板。
    
    // 可变参数模板类 继承方式展开参数包
    // 可变参数模板类的展开一般需要定义2 ~ 3个类,包含类声明和特化的模板类
    template<typename... A> class BMW{};  // 变长模板的声明
    
    template<typename Head, typename... Tail>  // 递归的偏特化定义
    class BMW<Head, Tail...> : public BMW<Tail...>
    {//当实例化对象时,则会引起基类的递归构造
    public:
        BMW()
        {
            printf("type: %s
    ", typeid(Head).name());
        }
    
        Head head;
    };
    
    template<> class BMW<>{};  // 边界条件
    
    // 模板递归和特化方式展开参数包
    template <long... nums> struct Multiply;// 变长模板的声明
    
    template <long first, long... last>
    struct Multiply<first, last...> // 变长模板类
    {
        static const long val = first * Multiply<last...>::val;
    };
    
    template<>
    struct Multiply<> // 边界条件
    {
        static const long val = 1;
    };
    
    
    void mytest()
    {
        BMW<int, char, float> car;
        /*
        运行结果:
            type: f
            type: c
            type: i
        */
    
        std::cout << Multiply<2, 3, 4, 5>::val << std::endl; // 120
    
    
        return;
    }
    
    
    int main()
    {
        mytest();
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    MySQL Unable to convert MySQL datetime value to System.DateTime 解决方案
    Zend 无限试用
    SQL 触发器
    C# 多线程示例
    JS 实现打印
    apache开启.htaccess
    MySQL 安装包下载教程
    js系列(10)js的运用(二)
    js系列(9)js的运用(一)
    js系列(8)简介
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/7787514.html
Copyright © 2011-2022 走看看