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;
}
原文地址:https://www.cnblogs.com/yejianfei/p/2773722.html