zoukankan      html  css  js  c++  java
  • C++11标准新增可变参数模板(variadic template)

      C++ 11标准新增加了“可变参数模板”(variadic template)

      可变参数模板中,模板的typename个数是可变长度的。下面给个例子,已在g++ 4.6.1上编译通过,并成功运行。

    /*
     * C++11标准  可变参数模板(variadic template)  样例
     *
     *
     *               Copyright  ©   叶剑飞  2012
     *
     *
     * 编译命令:
     *       g++ myPrintf.cpp -o myPrintf -std=c++0x -Wall
     *
     */
    
    #include <iostream>
    #include <cstdlib>
    #include <stdexcept>
    
    void myPrintf(const char * s)
    {
        while (*s)
        {
            if (*s == '%')
            {
                if (*(s + 1) == '%')
                {
                    ++s;
                }
                else
                {
                    throw std::runtime_error("invalid format string: missing arguments");
                }
            }
            std::cout << *s++;
        }
    }
    
    template<typename T, typename... Args>
    void myPrintf(const char * s, T value, Args... args)
    {
        while (*s)
        {
            if (*s == '%')
            {
                if (*(s + 1) == '%')
                {
                    ++s;
                }
                else
                {
                    std::cout << value;
                    myPrintf(s + 1, args...); // 即便 *s == 0 的时候,也调用,以便用于检测多余的参数。
                    return;
                }
            }
            std::cout << *s++;
        }
        throw std::logic_error("extra arguments provided to myPrintf");
    }
    
    int main ( )
    {
        // 每一个百分号,输出一个参数
        myPrintf( "a%bcde%fghij%kl%mn\n", 12, "interesting", 8421, "very_interesing" );
        return EXIT_SUCCESS;
    }
  • 相关阅读:
    .NET 动态脚本语言
    webParts与Web部件
    比较JqGrid与XtraGrid
    XtraGrid滚轮翻页
    Python------继承
    Python 私有化类的属性
    Python print 输出不换行,只有空格
    Python--函数参数类型
    手推FP-growth (频繁模式增长)算法------挖掘频繁项集
    Python 返回多个值+Lambda的使用
  • 原文地址:https://www.cnblogs.com/yejianfei/p/2773722.html
Copyright © 2011-2022 走看看