IntelliJ Reshaper will offer fantastic inspection hints for the following:
printf("%s", 5); // have warning inspection hint.
Which will indicate that the format string does not match the type of its arguments. I love this.
Now I want to make a custom function have the same feature, how to implement it?
https://www.jetbrains.com/help/resharper/Code_Analysis__String_Formatting_Methods.html#custom
Similar to the custom string formatting methods mentioned in the link above, I tried to use the following code in Visual C++, but it didn't work. It seems that it only has an effect on C#.
#include <string>
std::string format_v(const char* formatString, va_list args)
{
std::string result;
auto len = _vscprintf(formatString, args);
if (len == -1)
return result;
result.resize(len);
vsprintf_s(&result[0], result.size() + 1, formatString, args);
return result;
}
[StringFormatMethod("formatString")]
std::string format(const char* formatString, ...)
{
std::string result;
if (!formatString)
return result;
va_list args;
va_start(args, formatString);
result = format_v(formatString, args);
va_end(args);
return result;
}
int main()
{
printf("%s", 5); // have warning inspection hint.
std::string msg = format("%s", 122); // no inspection hint.
return 0;
}
build failed:
warning C4467: usage of ATL attributes is deprecated
error C2337: 'StringFormatMethod': attribute not found
I try to clarify this problem, and hope you can understand it. Sorry for my bad English.