Prajkata
Prajkata

Reputation: 65

How to get all arguments in variable argument method?

I have a variable argument function called from ruby script as follows:

static myMethod(VALUE exc, const char *fmt, ...)
{
  // Implementation of myMethod which requires all the arguments 
  // how to access the all arguments.
}

Can anyone tell me how to access all the arguments. Thanks in advance.

Upvotes: 1

Views: 431

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299950

In C++11, the variadic templates have been introduced, which allow a type safe alternative for variadic functions.

The typical example is a variant of the traditional printf, from Wikipedia:

void printf(const char *s)
{
    while (*s) {
        if (*s == '%' && *(++s) != '%')
            throw std::runtime_error("invalid format string: missing arguments");
        std::cout << *s++;
    }
}

template<typename T, typename... Args>
void printf(const char *s, T value, Args... args)
{
    while (*s) {
        if (*s == '%' && *(++s) != '%') {
            std::cout << value;
            ++s;
            printf(s, args...); // call even when *s == 0 to detect extra arguments
            return;
        }
        std::cout << *s++;
    }
    throw std::logic_error("extra arguments provided to printf");
}

Note how T in the example above is a true type (though unknown in the template definition).

The main advantage is that you can safely pass any type/class to variadic templates, while for C-style variadic you are limited to built-in types (including pointers). Using variadic template still requires some learning though.

Upvotes: 3

AnT stands with Russia
AnT stands with Russia

Reputation: 320551

What does "access the all arguments" mean? You can access the variadic arguments one by one by using macros from va_... group (va_start, va_arg etc.), the way it is usually done.

Upvotes: 5

Related Questions