First, I want to mention that Variadic arguments is a C language feature which just was inherited in C++ (and kept for compability).
Modern C++ provides type save alternatives like Parameter pack, Initializer Lists which IMHO should be preferred.
However, that said, now a possible solution.
I once found it when I tried to mimic something similar like printf()
. At that time, I noticed the existance of vprintf()
and got why and for what it is good for.
This is the basic idea, I tried to solve the dilemma of OP:
#include <cstdarg>
#include <iostream>
class A {
public:
A(float f)
{
std::cout << "A::A(" << f << ")\n";
}
A(int n, ...)
{
std::cout << "A::A(";
va_list args;
va_start(args, n);
getArgs(n, args);
va_end(args);
std::cout << ")\n";
}
protected:
A()
{
std::cout << "A::A()\n";
}
void getArgs(int n, va_list args)
{
std::cout << n;
for (int i = 0; i < n; ++i) {
float arg = va_arg(args, double); // Please, note, float is not a standard argument type.
std::cout << ", " << arg;
}
}
};
class B: public A {
public:
B(float f): A(f)
{
std::cout << "in B::B(float)\n";
}
B(int n, ...)
{
std::cout << "in B::B(";
va_list args;
va_start(args, n);
getArgs(n, args);
va_end(args);
std::cout << ")\n";
}
};
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
std::cout << "Test flavors of A::A():\n";
DEBUG(A a1(1.23f));
DEBUG(A a2(3, 1.2f, 2.3f, 3.4f));
std::cout << "Test flavors of B::B():\n";
DEBUG(B b1(1.23f));
DEBUG(B b2(3, 1.2f, 2.3f, 3.4f));
}
Output:
Test flavors of A::A():
A a1(1.23f);
A::A(1.23)
A a2(3, 1.2f, 2.3f, 3.4f);
A::A(3, 1.2, 2.3, 3.4)
Test flavors of B::B():
B b1(1.23f);
A::A(1.23)
in B::B(float)
B b2(3, 1.2f, 2.3f, 3.4f);
A::A()
in B::B(3, 1.2, 2.3, 3.4)
Live Demo on coliru
Hint:
An IMHO common trap with variadic arguments are the default argument promotions, mentioned e.g. here: Variadic arguments – Default conversions. (I remarked this with a resp. comment where it was relevant in my sample code.)