C++ 可变参数模板

来源:互联网 发布:斗拱尺寸公式算法 编辑:程序博客网 时间:2024/05/23 01:17

C++ 可变参数模板

flyfish

C++98版本不支持 ,C++11版本以上支持
Arguments 是参数包(Parameter pack)
类 classname 可以接受可变参数个数

template<typename... arg> class custom_tuple {};custom_tuple<> c1;custom_tuple<int> c2;custom_tuple<float, bool> c3;custom_tuple<long, std::vector<int>, std::string> c4;

至少一个template

#include "stdafx.h"#include <vector>#include <iostream>void tprintf(const char* format) // base function{    std::cout << format;}template<typename T, typename... Targs>void tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function{    for (; *format != '\0'; format++) {        if (*format == '%') {            std::cout << value;            tprintf(format + 1, Fargs...); // recursive call            return;        }        std::cout << *format;    }}int main(){    tprintf("% world% %\n", "Hello", '!', 123);    system("pause");}

另一个种方法
C++编程 –实现可变参数的函数