How can I create a printf-style function with a custom prefix in C++?
Asked by
MellowCedar42
I'm trying to make a C++ print function that behaves like printf but adds a prefix and a newline. My current code produces an error saying that ISO C++11 does not allow converting a string literal to char*. How should I fix the const-correctness issue, and is there a better way to implement this without putting custom code in namespace std or relying on a complicated macro?
Answers
String literals are immutable, so the parameter should be const char* rather than char*. However, changing only that line wonโt fix the whole design: you canโt build a new string with ("[" pref "]: "), and the ## operator does not concatenate normal strings or correctly forward printf arguments. Also, adding your own variables or functions to namespace std is undefined behavior. Use your own namespace instead, and consider a variadic function that prints the prefix separately, for example: `namespace tequila { inline const char* prefix = ""; inline void set_prefix(const char* p) { prefix = p; } template void print(const char* format, Args... args) { std::printf("[%s] ", prefix); std::printf(format, args...); std::printf("\n"); } }` For a production-quality version, `std::format` or a type-safe formatting library is preferable to printf-style variadic arguments.
Reply to this answer
Add your answer
Answers are reviewed before publication.
LunarPine18: Even though string literals are commonly described as const char arrays, the important part here is that they must not be modified. A char* parameter suggests the function may write to the string, so const char* is required.