Differentiate between pointers and data variables
given a function with a variable number of parameters...
void function(int count,...)
{
...
}
how do i differentiate between pointers and data variables... given i don't know the types beforehand. i.e
char *p=new char();
*p='v';
function(2,5,p);
how to know if p is a pointer so t开发者_开发知识库hat it can be handled that way inside the function... i.e if it were a pointer i would use *p else only p etc. the function to be designed is thus going to be a general function,taking pointers and data ..
any type of answer is acceptable.. thank you in advance...
This is not possible using variable arguments. The type of the arguments must be known when calling va_arg.
One possible way to do this is pass pointers to self describing data like variants.
Very nice explanation HERE
The short answer is that you can't. The variable argument list doesn't have type information. That is why functions such as printf
and scanf
require a format string
printf("%s %d\n","here is the magic number",42);
You need to either document how your function should be called orr use a format string like printf
does.
Variable argument list are support in C++ but are not object oriented or typesafe and there are better alternatives. One C++ alternative is to use a construct such as the <<
operator as used with cout (the C++ equivalent of printf
)
cout << "here is the magic number" << ' ' << 42 << endl;
You can implement this for your own class like this
class VarArgs
{
public:
VarArgs & operator << (int value)
{
//do something
return *this;
}
VarArgs & operator << (char value)
{
//do something
return *this;
}
VarArgs & operator << (char *value)
{
//do something
return *this;
}
//etc.
};
精彩评论