I was trying to reduce my code and I found something weird with variadic functions (it's most certainly due to my lack of knowledge though)
So I have that piece of code that works :
void Text::textTypePtr(Root* text, ...)
{
va_list args;
va_start(args, text);
Interact::ModifiedKey modKey = va_arg(args, Interact::ModifiedKey);
Keyboard::Key key = va_arg(args, Keyboard::Key);
static_cast<Text*>(text)->textType(modKey, key);
va_end(args);
}
and then, this piece of code that reverses the args order
void Text::textTypePtr(Root* text, ...)
{
va_list args;
va_start(args, text);
static_cast<Text*>(text)->textType(va_arg(args, Interact::ModifiedKey), va_arg(args, Keyboard::Key));
va_end(args);
}
I'm now scared that the first piece of code worked by some miracle, can someone maybe help me to understand what's going on?
The first version is correct. Statements are executed in order, so you can be confident the first variadic argument will be assigned to modKey and the second will be assigned to key.
The second version is depending on unspecified behavior. The relative order of evaluation of arguments to a function is unspecified. So it can evaluate either va_arg() expression first, which means that it could assign the wrong variadic argument to each parameter of the textType() function.
Related
I have a C++ class that is the frontend for a logging system. Its logging function is implemented using C++11's variadic templates:
template <typename... Args>
void Frontend::log(const char *fmt, Args&&... args) {
backend->true_log(fmt, std::forward<Args>(args)...);
}
Each logging backend implements its own version of true_log, that, among other things, uses the forwarded parameters to call vsnprintf. E.g.:
void Backend::true_log(const char *fmt, ...) {
// other stuff..
va_list ap;
va_start(ap, fmt);
vsnprintf(buffer, buffer_length, fmt, ap);
va_end(ap);
// other stuff..
}
Everything works great, and I am happy.
Now, I want to add a static check on the log() parameters: specifically, I would like to use GCC's printf format attribute.
I started by tagging the log() function with __attribute__ ((format (printf, 2, 3))) (as this is the first "hidden" parameter, I need to shift parameter indices by one). This does not work, because if fails with a compilation error:
error: args to be formatted is not ‘...’
Then, I tried to add the same attribute to the true_log() function. It compiles, but no error checking is actually performed: I tried to pass to log() some invalid format/variable combinations, and no warning was issued. Maybe this kind of check is "too late", or, in other words, the information about the variable has been lost in the chain of calls?
As a last resort, if I annotated log() with __attribute__ ((format (printf, 2, 0))), I would receive warnings about wrong format strings, but no diagnostic would be issued for invalid format/variable combinations.
Summarizing the problem: how can I have full format checking from GCC if I use C++11's variadic templates?
I don't believe you can. I bet that GCC only verifies the format string if it's a literal. This is why putting the format attribute on true_log doesn't work - that function is called with what looks (syntactically) like a runtime-determined string. Putting it on log directly would circumvent that, but would require format attributes to support variadic template, which you proved it doesn't.
I suggest that you look at more C++-ish ways to do formatted output. There is, for example, boost::format which works kind of like printf, but dynamically verifies that the number and types of the parameters types match the format string. It doesn't use variadic templates, though, but instead consumes parameters fed to it (via operator %) one-by-one.
For the record, I ended up removing the C++11 variadic templates altogether, and using a traditional va_list.
__attribute__((format(printf, 2, 3)))
void Frontend::log(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
backend->true_log(fmt, ap);
va_end(ap);
}
void Backend::true_log(const char *fmt, va_list ap) {
// log the message somehow
}
There is a workaround if you are willing to use a macro.
There are constructs that will cause the compiler to do the checking for you, but will not generate any called code. One such construct is sizeof. So, you could use a macro for your logger to pass the arguments to printf directly but in the context of a sizeof calculation, and then call the logger itself.
The reason to use a macro is to make sure the format string is treated just like a string literal would be treated.
In the illustration below, I treat the sizeof calculation as a throwaway argument, but there should be other ways to apply the same technique.
template <typename... Ts>
void Frontend::log(size_t, const char *fmt, Ts&&... args) {
backend->true_log(fmt, std::forward<Ts>(args)...);
}
#define log(...) log(sizeof(printf(__VA_ARGS__)), __VA_ARGS__)
Try it online!
Of course, this is a workaround. There are numerous reasons not to use a macro. And in this case, the log macro would interfere with any other function or method with the same name.
This is my current function which works but is not type safe and can get annoying sometimes.
void Debug::Log(LogLevel level, const char* format, ...)
{
va_list args;
va_start(args, format);
cout << "[" << LogLevelToString(level) << "]\t";
vprintf(format, args);
va_end(args);
cout << endl;
}
As you can see I would like for the arguments passed in to be formatted by the format specified. I know std::cout has formatting capabilities but I haven't found anything which explains how it can be implemented with the C va_list.
Basically the main points are: I want to keep the the same behavior but with a type safe more modern method, I need to std::cout so I can easily redirect output to file or where ever I need to.
Helpful points: from the format I can determine how many parameters where passed in, is there a way to loop through va_list arguments so I can pass them to cout individually?
Thanks
For easy redirection, you can certainly use vfprintf(). For individual control/cout of each argument, I think the only way is to va_arg() through the list using the correct type, i.e. an_int = va_arg(the_va_list, int);, a_double = va_arg(the_va_list, double);, and so on. I haven't tried but I think va_arg will do the proper increment on the memory using the type passed to it.
I have a C++ class that is the frontend for a logging system. Its logging function is implemented using C++11's variadic templates:
template <typename... Args>
void Frontend::log(const char *fmt, Args&&... args) {
backend->true_log(fmt, std::forward<Args>(args)...);
}
Each logging backend implements its own version of true_log, that, among other things, uses the forwarded parameters to call vsnprintf. E.g.:
void Backend::true_log(const char *fmt, ...) {
// other stuff..
va_list ap;
va_start(ap, fmt);
vsnprintf(buffer, buffer_length, fmt, ap);
va_end(ap);
// other stuff..
}
Everything works great, and I am happy.
Now, I want to add a static check on the log() parameters: specifically, I would like to use GCC's printf format attribute.
I started by tagging the log() function with __attribute__ ((format (printf, 2, 3))) (as this is the first "hidden" parameter, I need to shift parameter indices by one). This does not work, because if fails with a compilation error:
error: args to be formatted is not ‘...’
Then, I tried to add the same attribute to the true_log() function. It compiles, but no error checking is actually performed: I tried to pass to log() some invalid format/variable combinations, and no warning was issued. Maybe this kind of check is "too late", or, in other words, the information about the variable has been lost in the chain of calls?
As a last resort, if I annotated log() with __attribute__ ((format (printf, 2, 0))), I would receive warnings about wrong format strings, but no diagnostic would be issued for invalid format/variable combinations.
Summarizing the problem: how can I have full format checking from GCC if I use C++11's variadic templates?
I don't believe you can. I bet that GCC only verifies the format string if it's a literal. This is why putting the format attribute on true_log doesn't work - that function is called with what looks (syntactically) like a runtime-determined string. Putting it on log directly would circumvent that, but would require format attributes to support variadic template, which you proved it doesn't.
I suggest that you look at more C++-ish ways to do formatted output. There is, for example, boost::format which works kind of like printf, but dynamically verifies that the number and types of the parameters types match the format string. It doesn't use variadic templates, though, but instead consumes parameters fed to it (via operator %) one-by-one.
For the record, I ended up removing the C++11 variadic templates altogether, and using a traditional va_list.
__attribute__((format(printf, 2, 3)))
void Frontend::log(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
backend->true_log(fmt, ap);
va_end(ap);
}
void Backend::true_log(const char *fmt, va_list ap) {
// log the message somehow
}
There is a workaround if you are willing to use a macro.
There are constructs that will cause the compiler to do the checking for you, but will not generate any called code. One such construct is sizeof. So, you could use a macro for your logger to pass the arguments to printf directly but in the context of a sizeof calculation, and then call the logger itself.
The reason to use a macro is to make sure the format string is treated just like a string literal would be treated.
In the illustration below, I treat the sizeof calculation as a throwaway argument, but there should be other ways to apply the same technique.
template <typename... Ts>
void Frontend::log(size_t, const char *fmt, Ts&&... args) {
backend->true_log(fmt, std::forward<Ts>(args)...);
}
#define log(...) log(sizeof(printf(__VA_ARGS__)), __VA_ARGS__)
Try it online!
Of course, this is a workaround. There are numerous reasons not to use a macro. And in this case, the log macro would interfere with any other function or method with the same name.
I have been reading that some compilers support va_list with macros and users were able to overload the functionality with other macros in order to count the va_list.
With visual studio, is there a way to determine if the va_list is empty (aka count==0)? Basically I would like to know this condition:
extern void Foo(const char* psz, ...);
void Test()
{
Foo("My String"); // No params were passed
}
My initial thought was to do something like this:
va_list vaStart;
va_list vaEnd;
va_start(vaStart, psz);
va_end(vaEnd);
if (vaStart == vaEnd) ...
The problem is that va_end only sets the param to null.
#define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) )
#define _crt_va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
#define _crt_va_end(ap) ( ap = (va_list)0 )
I was thinking of maybe incorporating a terminator but I would want it to be hidden from the caller so that existing code doesnt need to be changed.
There is no way to tell how many arguments are passed through ..., nor what type they are. Variadic function parameters can only be used if you have some other way (e.g. a printf-style format string) to tell the function what to expect; and even then there is no way to validate the arguments.
C++11 provides type-safe variadic templates. I don't know whether your compiler supports these, or whether they would be appropriate for your problem.
I realize this question is fairly old, but I thought it might be helpful to flesh it out a bit. As Mike Seymour answered quite correctly, there is no absolutely reliable way to determine the number of arguments in a va_list. That's why the conventional way to define a variadic function is to include a parameter that has that information, like so: void func(const char *str, int count, ...);, which defines a contract your callers are supposed to abide by.
EDIT: The standard (7.16.1.1.3) is actually silent on the value returned by va_arg(vl, type) for any call past the end of the variable argument list. The most common case for most types is typed-zero. However, CAVEAT EMPTOR - it doesn't have to be.
The value returned from va_arg(vl, type) when there are no more arguments is a typed-zero value. For numeric types, it is 0. For pointers, it is a NULL pointer. For structs, it is a struct with all fields zeroed. If you elect to copy the va_list and try to count the copy, like so:
void func(const char *str, ...) {
va_list vl;
va_list vc;
int x;
int count;
count = 0;
va_start(vl, str);
va_copy(vc, vl);
do {
x = va_arg(vc, int);
if (x == 0) break;
count++;
} while (1)
va_end(vc);
.
.
. // do something, or something else,
. // based on the number of args in the list
.
va_end(vl);
You would have to make the assumption that the caller would abide by the contract not to pass a NULL or zero value in the list. Either way, you have to understand that the caller of a variadic function is responsible for abiding by the stated contract. So write your function, publish the contract, and sleep easy.
I am aware that my answer isn't an "orthodox" answer, however due to the limitation of the va_list macro, I found the following solution to work. We can look at a va_list as an array of chars, and even better, a null terminated one, so you can try
va_list argptr;
if(strcmp(argptr,""))
{
// not empty
}
else
{
// empty
}
I tried that and it worked for me.
I used Visual Studio 2013 Ultimate. The project type is Win32 Console Application. No compilation errors.
I have a function with following signature
char requestApiCall(int num, const wchar_t* pParams = 0, ...)
{
...
}
Now I want to to get all pParams in an array (or to be able to iterate over it). I know this is possible with some macros, but I have no idea how to do it.
Any help would be appreciated.
P.S. I'm using MinGW if it matters.
UPDATE
my question caused confusion. I will try to clarify (sorry for my grammar). Both Object Pascal and C# has the ability to pass unlimited amount of parameters to a method. In C# we achieve this with params keyword:
void Foo(params string[] strs)
{
...
}
Foo("first", "second", "another one", "etc");
I want to achieve same result in C++ without using any object/class. In my case, type safety is not a concern, but if there is a type safe way to achieve that goal, I will gladly hear your comments :)
Thanks
You need to look at the functions and macros declared in stdarg.h. Here is a tutorial that explains it.
http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html
I'm not sure what your function parameters are supposed to represent but I think you'll find that it needs to change.
By the way, I find that for C++ I can usually avoid variadic functions. This has the advantage of preserving type safety. Are you sure you really need a variadic function?
Using variadic function arguments is a dangerous and tricky business, and almost surely there is a better way - for example, you might pass an std::vector<std::wstring>& to your function!
OK, that said, here's how to use variadic arguments. The key point is that it is your responsibility to know the number and types of the arguments!
#include <cstdarg>
char requestApiCall(int num, const wchar_t* pParams, ...)
{
va_list ap; // the argument pointer
va_start(ap, pParams); // initialize it with the right-most named parameter
/** Perform magic -- YOU have to know how many arguments you are getting! **/
int a = va_arg(ap, int); // extract one int
double d = va_arg(ap, double) // one double
char * s = va_arg(ap, char*) // one char*
/* ... and so forth ... */
va_end(ap); // all done, clean up
}
Just for completeness, I would redefine the function as this:
char requestApiCall(std::vector<std::wstring> & params)
{
for (std::vector<std::wstring>::const_iterator it = params.begin(), end = params.end(); it != end; ++it)
{
// do something with *it
}
/* ... */
}
A good example of what you are trying to accomplish is the exec family of functions. exec() takes an variable list of arguments all of which are expected to be const char*. The last item is a NULL ((char*)0). The last item is the indicator for when the list of items is complete.
You can use the variadic macros in stdargs.h as others have described.