Simon Moles
Simon Moles

Reputation: 399

Variable Argument list with no named argument?

Is it possible to have a function with variable arguments and no named argument?

For example:

SomeLogClass("Log Message Here %d").Log(5);
SomeLogClass("Log Message Here %d").Error(5);

Upvotes: 1

Views: 1181

Answers (4)

Dov
Dov

Reputation: 8572

The right answer is no, you can't define only variable arguments, because the mechanism in C/C++ to do so uses a fixed argument in order to compute an address, like this:

void f(int a, ...) {
    va_list args;
    va_start(args, a); // without a, this macro DOESN'T WORK!!!


}

The answer you flagged gets around it by defaulting the arguments. But what this should teach the newbies is that defaulting the arguments doesn't mean that arguments aren't passed, it means that you don't have to type them.

void f (int a = 0, ...)

So when you call f you can write:

f();

but internally, it's writing f(0)

Upvotes: 0

daramarak
daramarak

Reputation: 6155

Where I am from we use this:

Log << "LogMessageHere: " << ErrorClass << 5 << whatever << std::endl;

It is not exactly an answer to you question, but it is a solution to your problem, and I think it is more c++ like.

Upvotes: 1

Dmitry
Dmitry

Reputation: 6780

Take a look at QString's arg methods. Those seem to be something you're looking for.

You can definitely roll your own, although implementation might turn out to be not really trivial, especially if you would like it to support printf format specifiers. If printf style is not necessary, chaining a replace_all kind of calls sounds doable.

Upvotes: 2

anon
anon

Reputation:

Can you write code like that above - yes you can. But you cannot portable write a variadic function without at least one non-variadic parameter. In printf(), for example, this is the format string. In other words, you can write function s like:

int printf( const char * format, ... );

but not:

int printf( ... );

Upvotes: 1

Related Questions