0

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 !!!

4
  • 2
    It works very well, does exactly what you assigned, "123456789" + 1 is "23456789", "123456789" + 2 is "3456789". You might want to repeat the pointer arithmetic. I'm having this unexpected result - and what have you expected, we cant guess and read your mind. Commented Mar 26, 2023 at 19:34
  • It is unclear why you believe "123456789" + i would be "the same", regardless of the value of i. Why perform this addition if you think it would have no effect? Commented Mar 26, 2023 at 19:38
  • That carefully about what the type of "123456789" is, and arithmetic on that type does. Commented Mar 26, 2023 at 19:41
  • If you instead made the function template <class First, class... Args> inline void log(First&& first, const Args&... args) you could log like this: log("I am a message to log ... ", "123456789", i); example Commented Mar 26, 2023 at 19:41

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.