The following code compiles in clang but not in gcc:
#include <cstdarg>
#include <iostream>
struct Base {
Base(const char* fmt, ...) __attribute__((format(printf, 2, 3))) {
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
}
};
struct Derived : public Base {
using Base::Base;
};
int main() {
Derived d("%d", 3);
return 0;
}
gcc complains:
<source>: In function 'int main()':
<source>:18:20: sorry, unimplemented: passing arguments to ellipsis of inherited constructor 'Derived::Derived(const char*, ...) [inherited from Base]'
18 | Derived d("%d", 3);
| ^
<source>:14:15: note: declared here
14 | using Base::Base;
| ^~~~
Compiler returned: 1
How can I salvage it to work with gcc?
A similar question is asked here, but that question does not have format-string-validation requirements. As such, the first answer does not seem applicable, while the second answer appears to demand a copy+paste of the contents of the base class's constructor.
The above code is a simple toy example. In my actual use-case, my base-class inherits from std::exception
, and allows me to conveniently construct an error message via printf-formatting and pass that message to an exception-constructor with a one-liner. I am open to any other approach that would allow me to define such a base-class along with derived-classes, all with compile-time printf-format-string-validation.