How can I implement a printf-style function with a custom prefix in C++?
Asked by
MellowOrbit42
I'm trying to create a C++ print() helper that behaves somewhat like printf(), but automatically adds a prefix and a newline. My current code stores the prefix in a char* and uses a variadic macro, but compilation fails with: "ISO C++11 does not allow conversion from string literal to char*." What is causing this error, and what would be a better way to implement the function?
Answers
String literals cannot be assigned to char* because they must not be modified. Use const char* for values that point to string literals. Also, putting your own variables and functions inside namespace std is undefined behavior, so use your own namespace instead.
Reply to this answer
The macro is problematic too: ## is for token pasting, and it cannot be used to combine a format string with arbitrary arguments the way this code attempts. If you keep a printf-style interface, pass the format and arguments directly to printf. For more type-safe code, consider using std::format or a formatting library instead of a macro.
Reply to this answer
The prefix construction is not valid C++ either. Expressions like ("[" pref "]: ") only work for adjacent literal strings, not for a runtime variable. A simple modern approach is to use std::string and a variadic template, for example: namespace tequila { inline std::string prefix; inline void set_prefix(const std::string& p) { prefix = "[" + p + "]: "; } template void print(const char* format, Args... args) { std::printf("%s", prefix.c_str()); std::printf(format, args...); std::printf("n"); } }
Reply to this answer
Add your answer
Answers are reviewed before publication.
QuartzMango19: The literal is effectively a const character array. If the prefix needs to be changed, store it in a std::string rather than trying to modify the literal itself.