How to wrap a function with variable length arguments? How to wrap a function with variable length arguments? c c

How to wrap a function with variable length arguments?


the problem is that you cannot use 'printf' with va_args. You must use vprintf if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)

You sample works as follows:

void myprintf(char* fmt, ...){    va_list args;    va_start(args,fmt);    vprintf(fmt,args);    va_end(args);}int _tmain(int argc, _TCHAR* argv[]){    int a = 9;    int b = 10;    char v = 'C';     myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b);    return 0;}


In C++11 this is one possible solution using Variadic templates:

template<typename... Args>void myprintf(const char* fmt, Args... args ){    std::printf( fmt, args... ) ;}

EDIT

As @rubenvb points out there are trade-offs to consider, for example you will be generating code for each instance which will lead to code bloat.


I am also unsure what you mean by pure

In C++ we use

#include <cstdarg>#include <cstdio>class Foo{   void Write(const char* pMsg, ...);};void Foo::Write( const char* pMsg, ...){    char buffer[4096];    std::va_list arg;    va_start(arg, pMsg);    std::vsnprintf(buffer, 4096, pMsg, arg);    va_end(arg);    ...}