zoukankan      html  css  js  c++  java
  • C++ variadic template (1)

    可变参数模板以前没怎么谁用过,本次参考http://www.cnblogs.com/liyiwen/archive/2013/04/13/3018608.html

    对可变参数模板有了初步理解。

    使用variadic template 对printf 函数 进行编写。

    在我看来,可变模板的实现就是类似递归函数一样,通过一层一层调用自身方法完成对 parameter pack 一层一层的拆分,最终成为一个普通函数的过程。

    引用参考博文的图片

    程序如下:

    #include<iostream>
    #include<exception>
    #include<stdexcept>
    using namespace std;
    
    void printf1(const char *s)
    {
        while(*s){
            if(*s=='%'){
                if(*(s+1)=='%')
                    s++;
                else
                    throw runtime_error("invalid format of argument");    
            }
            cout << *s++;
        }
    
        return ;
    }
    
    template<typename T,typename... Args>
    void printf1(const char *s,T value,Args... args)
    {
        while(*s){
            if(*s=='%'){
                if(*(s+1)=='%')
                    s++;
                else{
                    cout << value;
                    printf1(s+2,args...);
                    return ;
                }
            
            }
            cout << *s++ ;
        
        }
        throw runtime_error("extract arguemnts provided to printf");
    
    }
    
    int main(int argc,char *argv[])
    {
        int i=23;
        char c='a';
        char *ch="hello world";
        printf1("this is int data %d
    ,this is string data %s
    this is short data %c
    ",i,ch,c);
    
        return 0;
    }

    程序只是实现了对数据的打印,并没有检查占位符 和实际参数的匹配

  • 相关阅读:
    Stream概念的理解
    nodejs进程间通信
    nodejs多进程spawn execFile exec fok方法的区别
    socket这个名词的理解
    Object.defineProperty方法总结
    git中HEAD^和HEAD~区别
    http常见的9种方法
    java怎么建立JAVA工程项目?
    树莓派mjpg-stream摄像头监控
    制作OS X 10.9 Mavericks 安装U盘
  • 原文地址:https://www.cnblogs.com/justboy/p/6625703.html
Copyright © 2011-2022 走看看