Skip to content

Instantly share code, notes, and snippets.

@DALDEI
Last active November 2, 2015 16:59
Show Gist options
  • Save DALDEI/a765d21988affe6d3337 to your computer and use it in GitHub Desktop.
Save DALDEI/a765d21988affe6d3337 to your computer and use it in GitHub Desktop.
C++ Portable Varargs for "Variadic Macros" - Portable to GCC and MS Visual Studio
/*
* Vairiadic Macros used in this form are portable to MSVC and GCC
* https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html#Varia
* https://msdn.microsoft.com/en-us/library/ms177415(v=vs.100).aspx
*/
#include <stdio.h>
#if __GNUC__
#define __FUNCSIG__ __PRETTY_FUNCTION__
#endif
void func( const char*fmt )
{
printf("%s: " , __FUNCSIG__ );
printf(fmt);
}
template<typename T1>
void func( const char*fmt , const T1& d1)
{
printf("%s: " , __FUNCSIG__ );
printf(fmt,d1);
}
template<typename T1,typename T2>
void func( const char*fmt , const T1& d1 , const T2& d2 )
{
printf("%s: " , __FUNCSIG__ );
printf(fmt,d1,d2);
}
template<typename T1,typename T2,typename T3>
void func( const char*fmt , const T1& d1 , const T2& d2, const T3& d3 )
{
printf("%s: " , __FUNCSIG__ );
printf(fmt,d1,d2,d3);
}
#define M1(...) func( __VA_ARGS__)
#define M2(M,...) func(M,## __VA_ARGS__)
#define M3(M,...) func(M,__VA_ARGS__)
int main(int ac,char**av)
{
M1("M1 hello\n");
M1("M1 one %d\n",1);
M1("M1 two %lf %s\n",(double).04,"string");
M1("M1 three %s %llX %3.8lf\n" , "hi" , 0xFF00FF00FF00FF00LL , (double) 1. / 3. );
M2("M2 hello\n");
M2("M2 one %1.9lf\n",(double)1.03);
M1("M2 two %lf %s\n",(double).04,"string");
M2("M2 three %hd %s %f\n",(short)25,"foo",1.2);
M3("M3 hello\n","");
M3("M3 one %d\n",1);
M3("M3 two %lf %s\n",(double).04,"string");
M2("M3 three %hd %s %f\n",(short)25,"foo",1.2);
}
@DALDEI
Copy link
Author

DALDEI commented Nov 2, 2015

Updated to show use of templates with explicit args indirecting to function with varargs to demonstrate that macro varargs do not need to directly call functions expecting varargs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment