3

Question How to use GCC's printf format attribute with C++11 variadic templates? is similar to mine, but I made more progress on the way to a solution.

GCC 4.8.1. Leaving aside the (in)efficiency issue, take the following method

template <typename ... Ts>
  __attribute__((format(printf, 1, 0)))
inline std::string stdprintf(const char *format, Ts ...ts) {
  char buf[256];
  snprintf(buf, 256, format, ts...);
  return std::string(buf);
}

According to the documentation, I had to make put 0 and not 2 in format(printf, 1, 0)) because the printf is used in a variadic way. The numbers represent which argument to the function is the format string, and which is the first argument to be checked for consistency with the % format specifiers. The 0 results in much weaker checking.

However, after template expansion, the function isn't really variadic. Is it just an issue that gcc insists on looking at this before expansion?

Community
  • 1
  • 1
Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53
  • I'm not sure what you mean by the statement that the documentation requires the third argument to be 0 because "the printf is used in a variadic way". The documentation says that you must specify 0 if the function is passed a va_list; that would *not* be a variadic call since it has a fixed number of arguments. You're not doing that here; what gcc complains about it that the function call (once the template is resolved) is *not* variadic, and the issue is that gcc will inspect the arguments *after* expansion. – rici Mar 07 '15 at 01:44
  • Well, if you put `format(printf, 1, 2)`, compile error. – Andrew Lazarus Mar 07 '15 at 06:36
  • if you for `format(printf, 1, 0)` it doesn't check the arguments! – Steve Lorimer Dec 08 '15 at 19:38

0 Answers0