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
}
Edit:
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
Use CONCATENATE, one of the text functions, to join two or more text strings into one string. Important: In Excel 2016, Excel Mobile, and Excel for the web, this function has been replaced with the CONCAT function.
As you know, the best way to concatenate two strings in C programming is by using the strcat() function.
The CONCAT function at least requires two parameters and this function can accept a maximum of 254 parameters.
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
}
For trivial projects this is one of the few things I use a MACRO
for. You can do something like this:
#define LOG(m) do{ std::cout << timestamp() << ": " << m << '\n'; }while(0)
// ...
LOG("error: [" << errno "] " << filename << " does not exist.");
Generally MACROS
should be avoided but there is no other way to get precisely this with a standard function. So...
Note: The empty condition do{...}while(0)
enables you to place the MACRO
in places that a MACRO
usually can't go if it contains multiple statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With