How can I implement a printf-style function with a custom prefix in C++?

0
0
Asked By MellowOrbit42 On

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?

3 Answers

Answered By BlueHarbor5 On

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"); } }

Answered By KiteRiver88 On

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.

Answered By CedarFox7 On

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.

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.