Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 939
Rico Chr. Avatar asked Jun 09 '18 17:06

Rico Chr.


People also ask

Which function is used for string concatenation?

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.

Which function in C can be used to append a string to another string?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.

How many parameters does the concatenate function accept for combining string values?

The CONCAT function at least requires two parameters and this function can accept a maximum of 254 parameters.


2 Answers

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
}
like image 106
HolyBlackCat Avatar answered Sep 17 '22 23:09

HolyBlackCat


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.

like image 39
Galik Avatar answered Sep 18 '22 23:09

Galik