简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM