Variadic templates

前端 未结 8 1924
野趣味
野趣味 2020-12-06 00:05

I have seen a lot of links introducing the variadic templates. But I have never seen any compilable example that demonstrates this approach.

Could someone provide me

8条回答
  •  春和景丽
    2020-12-06 00:48

    One of the simplest possible examples is the following implementation of max which isn't even templated on types.

    int maximum(int n)
    {
        return n;
    }
    
    template
    int maximum(int n, Args... args)
    {
        return max(n, maximum(args...));
    }
    

    Only slightly more complex is the canonical printf implementation:

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

提交回复
热议问题