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?
1 Answer
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.

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.