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?

Samuel Navarro Lou
  • 1,168
  • 6
  • 17
  • 1
    What's the exact error message you get? – πάντα ῥεῖ Jul 16 '15 at 06:47
  • 1
    If you could manage to find something that parses *incorrectly* instead of being a syntax error, **that** would be cool. – user541686 Jul 16 '15 at 06:49
  • @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. – nneonneo Jul 16 '15 at 06:57
  • Related [Can C++ code be valid in both C++03 and C++11 but do different things?](http://stackoverflow.com/q/23047198/1708801) – Shafik Yaghmour Jul 16 '15 at 09:26

1 Answers1

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
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • 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. – dau_sama Jul 16 '15 at 10:29