Katianie Katianie - 1 month ago 8
C++ Question

Checking variable arguments for type

I have the below a function I use for string concatenation, it takes in a variable length set of arguments. I want to check to make sure each element is
a char*. I was looking into using dymanic_cast but it cannot be used for char*.
How should I go about casting the arg?:

char* Concatenate(int numStrings, ...)
{
vector<char*> stringVectorArray;
va_list vargList;

if (numStrings > 0 && numStrings < MAX_STRING_BUFFER_SIZE)
{
//Store each of the arguments so we can iterate through them later.
va_start(vargList, numStrings);
for (int currIndex = 0; currIndex < numStrings; currIndex++)
{
char* item = (char*)(va_arg(vargList, char*));
if (item == NULL)
{
//Error: One of the parameters is not char*.
va_end(vargList);
return NULL;
}
else
{
stringVectorArray.push_back(item);
}
}
va_end(vargList);
}

return ConcatenateStrings(stringVectorArray);
}

Answer

You simply don't know. There is no well-defined way of knowing what the argument types are for a variable argument list.

You have to trust the caller to get it right: in C, use the (char*) notation, in C++ use reinterpret_cast.

The variadic templates of C++11 introduce type safety into variable argument lists.