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

时间:2022-08-20 06:02:09
#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 + ) != '\0' && *(str + ) != '\0' && *(str + ) == 'l' && *(str + ) == 'f')
{
ret.push_back("lf");
goto b;
}
if (*(str + ) != '\0')
{
ret.push_back(std::string{*(str+)});
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 ;
}