I want to write a formatToStr()
which receives a format in const char*
and returns the formatted string.
My formatToStr()
sometimes may not receive parameters, as printf()
function.
#include <string>
template<typename... Args>
static inline std::string formatToStr(const char* format, const Args&... args) {
char buff[1024];
snprintf(buff, sizeof(buff), format, args...);
return std::string(buff);
}
int main() {
printf("%s\n", FormatToStr("test").c_str());
return 0;
}
This code provides a warning:
$ g++ --version
g++ (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
...
$ g++ ./z.cpp
./z.cpp: In instantiation of ‘std::string formatToStr(const char*, const Args& ...) [with Args = {}; std::string = std::__cxx11::basic_string<char>]’:
./z.cpp:11:28: required from here
./z.cpp:6:17: warning: format not a string literal and no format arguments [-Wformat-security]
6 | snprintf(buff, sizeof(buff), format, args...);
| ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is there a way to write better code to remove this warning? I can always ignore
it, but I wish to solve it in a better way.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
...
#pragma GCC diagnostic pop
Thanks
Aucun commentaire:
Enregistrer un commentaire