简体   繁体   English

c ++使用va_arg调用超类构造函数

[英]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. 您的派生类将执行相同的vapacking体操,然后使用超级构造函数的列表形式。

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. 如果有一个数据成员只是为了构造扰乱你和你的类是可复制的或可移动的,你也可以放弃变量构造函数,而是有一个命名的静态成员函数来执行包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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