4

I am trying to use a very simple log function using variadic templates in C++:

void log(){}

template <typename T, typename... Types>
void log(T first, Types... arg)
{
    std::cout << first << " ";
    log(arg...);
}

int main()
{
    log(1,2);
    log(3, "four");
    log(5);
    log(6,"seven",8,9,10,11,12);
    log(13,14);

}

But in the output I am missing all the last arguments of the log function if the are integers (2, 5, 12 and 14) but not if they are strings ("four") !??. Why is that? What I am doing wrong?

output: 1 3 four 6 seven 8 9 10 11 13
9
  • 1
    Cannot reproduce. What compiler and command line switches are you using? Commented Jul 19, 2021 at 0:22
  • Can't reproduce, either. You are just going to have to debug the code to figure out what is happening on the calls that don't work. Commented Jul 19, 2021 at 0:39
  • thanks @PaulSanders, it is spooky, I am not aware of using anything special. It is a fresh project in a recently installed Visual Studio 2021 without any further modifications. I also tried with VS2019 and get the same result. Commented Jul 19, 2021 at 0:41
  • I can confirm the problem on VS 2019, and there doesn't seem to be any obvious workaround. Looks like an MSVC bug, although it's hard to see how such an obvious problem has escaped their attention. Commented Jul 19, 2021 at 0:45
  • Agree, It would be crazy if it was actually a bug. In any case, I will get away from variadic functions for now :DD thanks. Commented Jul 19, 2021 at 0:50

1 Answer 1

5

Mystery solved - when compiling with MSVC your choice of the name log is clashing with the log function in the standard library when there is only one numeric parameter. Since this doesn't print anything, output is missing.

Just use another name and it works.

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

1 Comment

"Fixing" #include is also a possibility: using <cmath> instead of <math.h> (and avoid using namespace std;).

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.