Topic: Type safe variable argument lists


Author: Steve Bold <100334.622@CompuServe.COM>
Date: 19 Mar 1995 11:33:23 GMT
Raw View
 There have been a number of threads about changes to the
C++ standard. I have a suggestion of my own which I'd welcome
comments on. People have talked about submitting requests to the
ANSI committee. How do you do this?

 What I'd like is to have is functions with type safe variable
argument lists. This doesn't appear to require much change to the
language:

 The syntax change would be to alter a function's
'argument-declaration-list' (r8.2.5) to allow an optional argument
after '...'. For example you could write:

 class print_context;
 int printf(const char *format,...,print_context context);

 Given this prototype, a call to the function such as:

  char *s = "hello";
  int i = 5;
  printf("%s : %d\n",s,i);

Would be interpreted by the compiler as though you had written:

 print_context _tmp("%s : %d",2);
 printf(s,_tmp);
 printf(i,_tmp);


 The translation rules would be:

 A temporary object of the type given in the prototype will
be created. Its arguments will be the fixed arguments of the
prototype, followed by an int giving the number of variable arguments.

 For each variable argument, the compiler will add a call to
a function of the same name but with two arguments, the variable
argument from the call and the context object.

 Finally the temporary object will be destroyed.

 The benefits of this change would be:

 1. Printf and similar functions in stdio could be made type
safe, and even extensible to user defined types.

 2. ostream (or a user defined derived class) could provide
a print function for those who don't like the '<<' syntax.

 3. New types of constructors for container classes could be
produced which would initialise the container with a list of values.
For example you might declare an object:

  array<int> myArray(1,2,3,4);

 For safety, such constructor declarations should be restricted
to classes whose base classes all declare constructors of a similar form,
and can therefore cope with multiple constructor calls for a single object.

 This isn't exhaustive, there are plenty of other uses for
variable argument lists.

Steve Bold

EXIT