2012-05-29 44 views
2

使用2010 MSVC,我得到了以下行爲:模板專業化與PTR-ref類型和特殊規則

template <class T> class Boogy 
{ 
public: 
    void Fn(T in) 
    { 
    } 

    void Fn2(const T& in) 
    { 
    } 
}; 

template <> void Boogy<int>::Fn(int in) //builds ok 
{ 
} 

template <> void Boogy<int*>::Fn(int* in) //builds ok 
{ 
} 

template <> void Boogy<int>::Fn2(const int& in) //builds ok 
{ 
} 

template <> void Boogy<int*>::Fn2(const int*& in) //DOES NOT BUILD 
{ 
} 

typedef int* intStar; 
template <> void Boogy<intStar>::Fn2(const intStar& in) //builds ok 
{ 
} 

很顯然,我想出了一個「砍」到我的問題整理出來,但爲什麼黑客是必要的?我們應該這樣做嗎?我所在的代碼庫有幾十個實例,其中模板類具有某些成員函數的一些特化 - 而不是整個類。一位同事堅持認爲這是不允許的。

TIA。

回答

5

應該int * const &。你有T = int *,所以const T = T const = int * const

記住U const &意思是「參照恆定U」,而不是「恆定參考U」 —後者沒有意義,因爲在C基準變量++是總是恆定的,即,不能重新插拔。在你的情況U是一個指針到整型,而不是一個指針給const-INT,這是兩種不同的類型。

你當然也可以添加一個單獨的專門爲int const *

template <> void Boogy<int const *>::Fn2(int const * const & in) { /* ... */ } 
+0

尼斯... ...微妙 –

+0

當然!當你「從右向左讀」時,它突然變得有意義。 Kerrek SB,你是那個讓Luke的X-Wing退出沼澤的小綠人嗎? ;-)至於對模板類的某些成員進行專門化的問題 - 沒關係,對吧? –

+1

@LuchianGrigore:這就是我爲什麼要去做廣告對* *前面加上'const'的英語和往常一樣,系統地,把'const' * *後的類型其資格。只有內部類可以勝任* *前,它太容易搞砸了:( –