variadic template(二)

重写 print 函数

 

#include<iostream>
using namespace std;

void printfX(const char *s)
{
  while (*s)
  {
    if (*s == '%' && *(++s) != '%')
      throw "invalid format string: missing arguments";
    std::cout << *s++;
  }
}

template<typename T, typename... Args>
void printfX(const char* s, T value, Args... args)
{
  while (*s)
  {
    if (*s == '%' && *(++s) != '%')
    {
      std::cout << value;
      printfX(s, args...); // call even when *s == 0 to detect extra arguments
      return;
    }
    std::cout << *s++;
  }
  throw "extra arguments provided to printf";
}

int main() {
    int* pi = new int;
    printfX("%d %s %p %f\n",15,"This is Ace",pi,3.1415926);
    return 0;
}

 

posted @ 2022-01-28 22:24  王清河  阅读(31)  评论(0编辑  收藏  举报