简体   繁体   中英

c++ calling superclass constructor with va_arg

I have a base class, which includes a constructor with variable argument list:

class Super {
public:
    Super(int num, ...);
...
}

Now, in my subclass constructor I need to somehow call this superclass constructor, but how do I do it? The usual thing, naturally, doesn't work:

class Sub {
public:
    Sub(int num, ...) : Super(???) { ... }
...
}

So what do I put into instead of ???

I do have another constructor that accepts a vector, but having one like this is a direct requirement from the client.

As with any variable function, always provide a list version, too:

void foo(int a, ...) { va_list ap; va_start(ap, a); vfoo(a, ap); va_end(ap); }

void vfoo(int a, va_list ap) { /* actual implementation */ }

Same here:

#include <cstdarg>

struct Super
{
    Super(int num, ...) : Super(num, (va_start(ap_, num), ap_)) { va_end(ap_); }
    Super(int num, va_list ap);

private:
    va_list ap_;
};

Your derived classes would perform the same vapacking gymnastics and then use the list form of the super constructor.

If having a data member just for the purpose of construction upsets you and your class is otherwise copyable or movable, you can also forgo the variable constructor and instead have a named, static member function that does the pack wrapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM