Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variadic template unusual example

What does the following construction mean?

#include <iostream>

template <int ...> struct s;

int main() {
    int i = s<,>::xxx;

    std::cout << i << std::endl;
}

It is compiled by gcc 4.4.5+ and when executed outputs 0.

like image 730
Igor Milyakov Avatar asked May 30 '12 10:05

Igor Milyakov


1 Answers

I rewrote the program to this:

template <int ...> struct s;

int main() {
    int i = s<,>::xxx;

    return i;
}

and compiled it with the -S-switch, to get assembly output that I cleaned up to the following:

main:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    -4(%rbp), %eax
        popq    %rbp
        ret

Now, my asm is a bit rusty, but the only significant code seems to be movl -4(%rbp), %eax, which sets the return value to whatever it can read from i. In other words, the program simply returns whatever was on top of the stack when the main function was entered. This seems to corroborate @jrok's comment that the initialization of i is somehow ignored. No code has been generated for the mystical s<,>::xxx-expression.

Bottom line; this looks like a compiler bug. The compiler should have given an error message.

Corroborating side note: I get identical assembly output for the program int main() { int i; return i; }.

like image 101
Magnus Hoff Avatar answered Oct 21 '22 19:10

Magnus Hoff