Boost logo

Boost :

From: John Fletcher (J.P.Fletcher_at_[hidden])
Date: 2006-09-27 11:24:18


Doug Gregor wrote:
> ...
>
> I think variadic templates are a big step forward for C++ libraries
> that deal with function objects, forwarding, and type-lists. If
> you're interested, please read the documentation, hack some code with
> the compiler, and tell your local C++ committee representative to
> vote for variadic templates in C++0x :)
>

I have tried out the compiler using the cygwin compiled code supplied.

I have implemented the printf example. I had a name clash with the
printf in the system, and renamed the local one printff.
The return in the recursion had to be modified:

       /*return*/ printf(++s, args...);
       return;

When I added this example:

     const char* more = "have nothing to do with the case %s %s\n";
     printff(more, "tra la");

the output is

have nothing to do with the case tra la tra la

instead of an exception for an extra format.

I hope this helps.

Source code of example attached.

John


// printex.cpp

// Variadic printf example from the manual.

#include <iostream>
#include <stdexcept>

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

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

int main()
{
  try {
    const char* msg = "The value of %s is about %g (unless you live in %s).\n";
    const char* another = "The flowers that bloom in the spring %s \n";
    const char* more = "have nothing to do with the case %s %s\n";

    printff(msg, std::string("pi"), 3.14159, "Indiana");

    printff(another, "tra la");
    printff(more, "tra la");

  } catch(std::runtime_error s) {
    std::cout << "Caught " << s.what() << std::endl;
  }
  return 0;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk