首页 > 其他 > 详细

随手撸一个简单的带检查的printf

时间:2019-06-22 18:05:31      阅读:82      评论:0      收藏:0      [点我收藏+]
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <cassert>

template<typename T> std::string t()     { return "?"; }
template<> std::string t<const char *>() { return "s"; }
template<> std::string t<char>()         { return "c"; }
template<> std::string t<int>()          { return "d"; }
template<> std::string t<unsigned>()     { return "u"; }
template<> std::string t<float>()        { return "f"; }
template<> std::string t<double>()       { return "lf"; }

template<typename T>
std::vector<std::string> operator+(std::vector<std::string> chs, T val)
{
    chs.push_back(t<T>());
    return chs;
}

template<typename... T>
std::vector<std::string> ty2ch(T... vals)
{
    return (std::vector<std::string>{} + ... + vals);
}

std::vector<std::string> format2ch(const char* str)
{
    std::vector<std::string> ret;

    while (*str != \0)
    {
        if (*str == %)
        {
            if (*(str + 1) != \0 && *(str + 2) != \0 && *(str + 1) == l && *(str + 2) == f)
            {
                ret.push_back("lf");
                goto b;
            }
            if (*(str + 1) != \0)
            {
                ret.push_back(std::string{*(str+1)});
                goto b;
            }
        }
b:
        ++str;
    }
    return ret;
}

template<typename... T>
int Tprintf(const char* format, T... vals)
{
    auto ch_format = format2ch(format);
    auto ch_vals = ty2ch(vals...);
    assert(ch_format == ch_vals);

    return printf(format, vals...);
}

int main(int argc, char *argv[])
{
    Tprintf("this is a string %s", "hahah");

    return 0;
}

 

随手撸一个简单的带检查的printf

原文:https://www.cnblogs.com/sinx/p/11069597.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!