Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
Samuel Navarro Lou Avatar asked Mar 15 '23 09:03

Samuel Navarro Lou


1 Answers

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
like image 61
nneonneo Avatar answered Mar 23 '23 18:03

nneonneo