user3384414 user3384414 - 1 month ago 6
C++ Question

Pass variable argument list to base constructor in C++

Is it possible in C++ to pass a variable argument lists to a base constructor?

I could just copy the code of the base constructor to the derived class, an handle the variable argument list there, but that would lead to unwanted code duplication.

This is what I tried so far:

class A{
public:
A(const char * fmt,...){
va_list ap;
va_start( ap, fmt );
vprintf(fmt,ap);
va_end(ap);
};
};

class B: public A{
public:
B(const char * fmt,...):A(fmt){;};
};

int main(){
B("%d\n",42);
}


But the constructor doesn't pass the variable arguments to the base class constructor.

Answer

Just use variadic templates (and drop this C-style stuff):

struct A {
     template<typename ... Args>
     A(const char * fmt, Args&& ... args) {
          printf(fmt,std::forward<Args>(args) ...);
     };
};

struct B: public A {
  template<typename ... Args>
  B(const char * fmt, Args&& ... args) : A(fmt, std::forward<Args>(args) ...) {}
};

Example:

B("Print %d and %s",1,"hello");  //prints "Print 1 and hello"

DEMO

Comments