您的位置:首页 > 编程语言 > C语言/C++

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

2012-11-16 17:58 253 查看
  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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: