2010-12-13 35 views
5

我不知道爲什麼這些代碼無法編譯。我在Visual C++ 2010和gcc中用-std = C++ 0x進行了測試。有人提出一些建議? 謝謝!關於C++ 0x參考摺疊的問題

template<typename T> 
class Foo 
{ 
public: 
void test(const T&){cout<<"const";} 
void test(  T&){cout<<"non const";} 
}; 

int main() 
{ 
int a; 
Foo<int&> f; 
} 

編譯錯誤: '無效美孚::測試(T)':成員函數已經定義或聲明

偏偏這個可以編譯?

template<typename T> void foo(const T&){cout<<"const"; } 
template<typename T> void foo(T&){cout<<"non const"; } 
int main() 
{ 
    int a; 
    foo<int&>(a); 
} 

心中已經讀的C++ 0x的文章說:T & & ==牛逼&,所以常量牛逼& & ==常量牛逼&?

回答

8

此:

Foo<int&> f; 

引起此實例:

class Foo<int&> 
{ 
public: 
void test(int&); 
void test(int&); 
}; 

const施加到類型,它是引用是一個空操作。與基準數據成員在非靜態成員函數操作比較:

struct A { 
    int &ref; 

    // valid: const member function doesn't treat "ref" as "const int&". 
    void operate() const { 
    ref = 0; 
    } 
}; 

你要通過intFoo<...>來實現自己的目標。

13

i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?

實際上,這並沒有多大意義。恕我直言,這是更好地把這個變成一個表:

T  T&  const T  const T& 
--------------------------------------- 
int  int& const int const int& 
int& int& int&   int& 
     (1)  (2)   (1+2) 

1: Reference collapsing in action 
2: const applies to the reference and is therefore ignored 

如果T已經是一個參考(第二行)const T的常量適用於參考而不是裁判。但是,從初始化後不能引用另一個對象的意義上說,引用本質上是恆定的,因此在這裏忽略const。你可以把它看作「const collapsing」。 ;-)

1

對於第二個問題,這兩個實例化函數具有相同的參數類型,並且都是模板(如果一個是模板,另一個是非模板函數,重載解析將選擇後者),所以重載決議將選擇更專業的模板。通常const T &是比T &更專門化的類型,所以調用第一個模板函數。