Valid C++03 template code won't compile in C++11
Asked Answered
C

1

5

I have come across a small (easily solvable though) problem while writing valid C++03 template code, which compiles normally, that will not compile when using the C++11 dialect.

The problem arises at the template parameter resolution. Let this code be an example of this:

template <uint32_t number>
struct number_of_bits {
    enum  {
        value = 1 + number_of_bits<number >> 1>::value
    };
};

template <>
struct number_of_bits<0> {
    enum  {
        value = 0
    };
};

Since C++11 allows now ">>" to finish a template parameter list that takes a templated parameter as the last argument, it creates a problem when parsing this code.

I am using GCC (version 4.8.1) as my compiler, and it compiles normally using the command line:

g++ test.cc -o test

But it fails to compile when I add the -std=c++11 command line switch:

g++ -std=c++11 test.cc -o test

Is this a C++11 language feature or is it a bug in GCC? is this a known bug if it's the case?

Christy answered 16/7, 2015 at 6:44 Comment(4)
What's the exact error message you get?Visionary
If you could manage to find something that parses incorrectly instead of being a syntax error, that would be cool.Charleycharlie
@Mehrdad: I think it would be very hard. The >> necessarily closes 0 template arguments in C++03 but closes 2 template arguments in C++11. I am not sure how you would close the 2 unclosed arguments in C++03 without causing a compile failure on C++11.Rolfe
Related Can C++ code be valid in both C++03 and C++11 but do different things?Filippa
R
7

Clang++ gives me a warning in -std=c++03 mode:

test.cpp:6:43: warning: use of right-shift operator ('>>') in template argument
      will require parentheses in C++11 [-Wc++11-compat]
        value = 1 + number_of_bits<number >> 1>::value
                                          ^
                                   (          )

And indeed, in C++11 the parsing rules were revised so that >> always closes template parameters in template context. As the warning notes, you should just put parens around the parameter to fix the parsing issue:

value = 1 + number_of_bits<(number >> 1)>::value
Rolfe answered 16/7, 2015 at 6:47 Comment(1)
and that's why clang's diagnostics are great. I wish I could have them in gcc too, as I have to daily work with it.Gynarchy

© 2022 - 2024 — McMap. All rights reserved.