簡體   English   中英

有效的C ++ 03模板代碼無法在C ++ 11中編譯

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

在編寫正常編譯的有效C ++ 03模板代碼時,我遇到了一個小的(很容易解決的)問題,在使用C ++ 11方言時無法編譯。

問題出現在模板參數分辨率上。 讓這段代碼成為一個例子:

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

由於C ++ 11現在允許“>>”完成一個模板參數列表,該列表將模板化參數作為最后一個參數,因此在解析此代碼時會產生問題。

我使用GCC(版本4.8.1)作為我的編譯器,它使用命令行正常編譯:

g++ test.cc -o test

但是當我添加-std=c++11命令行開關時它無法編譯:

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

這是一個C ++ 11語言功能還是GCC中的一個錯誤? 這是一個已知的錯誤,如果是這樣的話?

Clang ++在-std=c++03模式中給出了警告:

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
                                          ^
                                   (          )

實際上,在C ++ 11中,修改了解析規則,以便>>始終在模板上下文中關閉模板參數。 正如警告所述,您應該在參數周圍放置一些parens來修復解析問題:

value = 1 + number_of_bits<(number >> 1)>::value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM