I have created a class which has a variadic template method. This method calls printf
function. When passing zero arguments to the method, I get a compile warning by gcc saying:
warning: format not a string literal and no format arguments [-Wformat-security]
A simplified class example is:
class printer{
std::map<int,std::string> str;
public:
printer(){
str[0] = "null\n";
str[1] = "%4d\n";
str[2] = "%4d %4d\n";
str[3] = "%4d %4d\n%4d\n";
}
template<typename ...Args>
void print(Args... args){
printf(str[sizeof...(args)].c_str(),args...);
}
};
When using
printer p;
p.print(23);
p.print(345,23);
everything compiles smoothly, but when using
printer p;
p.print();
I get the compile warning
main.cpp: In instantiation of ‘void printer::print(Args ...) [with Args = {}]’:
main.cpp:23:11: required from here
main.cpp:17:50: warning: format not a string literal and no format arguments [-Wformat-security]
printf(str[sizeof...(args)].c_str(),args...);
Of course if I just call
printf("null\n");
no warning appears.
Could someone explain why this is happening?
Can I remove warning without disabling the -Wformat-security
flag?