我创建了一个具有可变参数模板方法的类.这个方法调用printf函数.将零参数传递给方法时,我得到gcc的编译警告说:
警告:格式不是字符串文字而没有格式参数[-Wformat-security]
一个简化的类示例是:
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...);
}
};
Run Code Online (Sandbox Code Playgroud)
使用时
printer p;
p.print(23);
p.print(345,23);
Run Code Online (Sandbox Code Playgroud)
一切顺利,但使用时
printer p;
p.print();
Run Code Online (Sandbox Code Playgroud)
我收到编译警告
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...);
Run Code Online (Sandbox Code Playgroud)
当然,如果我只是打电话
printf("null\n");
Run Code Online (Sandbox Code Playgroud)
没有警告出现.
有人可以解释为什么会这样吗?
我可以在不禁用-Wformat-security标志的情况下删除警告吗?