Igor Milyakov
Igor Milyakov

Reputation: 612

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.

Upvotes: 12

Views: 424

Answers (1)

Magnus Hoff
Magnus Hoff

Reputation: 22089

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; }.

Upvotes: 13

Related Questions