2012-02-17 54 views
4
1 #include <cstdlib> 
2 #include <iostream> 
3 
4 enum { SIZE_PER_CHUNK = ((1<<16)/sizeof(unsigned)) }; 
5 
6 class TrueType {} ; 
7 class FalseType {} ; 
8 
9 template< std::size_t V, bool B = (((V) & ((V) - 1)) == 0) > class IsPowerOfTwo_; 
10 template< std::size_t V > class IsPowerOfTwo_< V, true > : public TrueType {}; 
11 template< std::size_t V > class IsPowerOfTwo_< V, false > : public FalseType {}; 
12 
13 typedef IsPowerOfTwo_<SIZE_PER_CHUNK> IsPowerOfTwo; 
14 
15 
16 int main() { 
17  IsPowerOfTwo p2; 
18  
19  std::cout << "Hello World!" << std::endl; 
20  return 0; 
21 } 

下面的代碼編譯器警告給出了一個編譯器警告(GCC 4.6.2,/project/dfttools/compile/lnx-x86/gcc-4.6.2):關於模板

警告:在的「&」 [-Wparentheses]

警告點操作數到線13,但它可能與表達在管線9

不限 - 建議周圍括號「」解?

+0

GCC有時指向其中temlpate被實例化,而不是其中的定義的行。把括號放在那裏,它依賴於運算符優先規則大多不是一個好主意。 – PlasmaHH 2012-02-17 10:33:06

+0

有圓括號! – rodrigo 2012-02-17 10:40:20

+0

請勿在您發佈的代碼中添加行號 - 它會使複製和粘貼在我的編譯器中嘗試不必要的困難。 (你可以在代碼中使用註釋來表示相關的特定行) – Flexo 2012-02-17 10:41:33

回答

1

對我來說看起來像一個編譯器錯誤。就好像編譯器從默認值B中刪除不需要的括號,然後它自己引發警告。

一種解決方法:

template<size_t V> struct IsPowerOfTwo_Helper 
{ 
    enum { value = V & (V - 1) }; 
}; 

template< std::size_t V, bool B = IsPowerOfTwo_Helper<V>::value == 0 > class IsPowerOfTwo_;