[comp.lang.c++] Extensible type-safe functions

glenn@synaptx.Synaptics.Com (Glenn Gribble) (10/15/90)

I want to make an extensible type-safe function.  A simple example
would be a type-safe printf().  There are a few problems:
    1) Storing the type information with the argument.
    2) Dealing with variable length arguments.
    3) Allowing a user to add more _safe_ types without recompiling.

The closest I have gotten is to make a function that takes
a "class varg&" argument.  A "varg" can be constructed from
an integer or whatever other kind of type is _safe_.  The "varg"
contains all the type dependant functionality.  The big problem
is that I can not increase the number of ways I can make a "varg"
without changing the header file for the "varg" class.  I would
like to be able to declare an operator like this:

    varg operator varg(double d);
    typedef varg& vargRef;
    varg& operator vargRef(double d);

When compiling this, I get "operator varg : not a member" errors.

Does anybody have any clues how to solve this problem?

Please note:  This has not a discussion about printf.  Please tell
me I want to use the streams package via email. :-)

I am including a simple example that demonstrates my approach.

#include <stdio.h>

class argBase {
public:
  virtual void printMe() = 0;
};

class intArg : public argBase {
public:
  int value;
  virtual void printMe() { printf("%d", value); }
  intArg(int x)	    	 { value = x; }
};

class varg {
  argBase *b;
public:
  void printMe()   { b->printMe(); }
  varg(int x)      { b = new intArg(x); }
};

// These do not compile
// varg operator varg(double d);
// typedef varg& vargRef;
// varg& operator vargRef(double d);

void safePrintf(const char *fmt, varg& arg1)
{
  for ( ; *fmt != '\0'; fmt++)
    if (*fmt == '%')
      arg1.printMe();
    else
      putchar(*fmt);
}

main()
{
  safePrintf("This is simple example #%\n", 1);
}
-- 
Glenn Gribble	 	glenn@synaptics.com 	uunet!synaptx!glenn