C++: How can i create a function that accepts concatenated strings as parameter?

  • A+

Can i design my logging-function in a way, that it accepts concatenated strings of the following form using C++?

int i = 1; customLoggFunction("My Integer i = " << i << "."); 


customLoggFunction( [...] ){     [...]     std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl } 


Using std::string as the attribute to the function works for the concatenated string, but then a passed non-concatenated string like customLoggFunction("example string") produces a compile-time error saying the function is not applicable for char[]. When i overload the function in the following way...

customLoggFunction(std::string message){...} customLoggFunction(char message[]){...} 

... the concatenated strings seize to work.

I uploaded the code: http://coliru.stacked-crooked.com/a/d64dc90add3e59ed


It's impossible to do with the exact syntax you asked for unless you resort to macros.

But if you don't mind replacing << with ,, then you can do following:

#include <iostream> #include <string> #include <sstream>  void log_impl(const std::string &str) {     std::cout << str; }  template <typename ...P> void log(const P &... params) {     std::stringstream stream;      (stream << ... << params);     // If you don't have C++17, use following instead of the above line:     // using dummy_array = int[];     // dummy_array{(void(stream << params), 0)..., 0};      log_impl(stream.str()); }  int main() {     log("1", 2, '3'); // prints 123 } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: