Search code examples
c++loggingvariadic-functions

CPP issue using variadic parameters (Args...) to log


I'm trying to log some things on my cpp app. I chose to go on variadic parameters.

My log functions :

inline void log() {}

template<class... Args>
inline void log(std::string_view first, const Args&... args)
{
    std::cout << first << std::endl;
    log(args...);
}

To test, I'm trying to log this message :

for (int i = 0; i < 10; ++i) {
    log("I am a message to log ... ", "123456789" + i);
}

I'm having this unexpected result (it should be the same number for each log message, no ?) :

I am a message to log ...
123456789
I am a message to log ...
23456789
I am a message to log ...
3456789
I am a message to log ...
456789
I am a message to log ...
56789
I am a message to log ...
6789
I am a message to log ...
789
I am a message to log ...
89
I am a message to log ...
9
I am a message to log ...

I think I'm missing something, somewhere in my code... I tried to run this code on 2 os (windows & linux mint), just to be sure x) !

Well, I'm stuck on this subject ...

Any ideas ? Thanks in advance !!!


Solution

  • As was mentioned in comments, your snippet behave as expected. See, problem is that you do "123456789" + i. "123456789" is const char*. So adding i is pointer arithmetic, where you in fact changing starting position of your data to print.

    Also already answered, fix you looking for is remove addition and make i new parameter of log function.