2013-01-20 15 views
4
#include <iostream> 

template <typename T> 
struct ref_exp{ 
    typedef T value_type; 
    typedef value_type& reference_type; 
    typedef const reference_type const_reference_type; 

    ref_exp(value_type data): _data(data){} 
    const_reference_type data() const {return _data;} 
    private: 
    value_type _data; 
}; 

int main(){ 
    ref_exp<int> exp1(2); 
    std::cout << exp1.data() << std::endl; 

    return 0; 
} 

上面的代碼無法編譯const_reference_type沒有編制,但常量VALUE_TYPE和編譯

ref.cpp: In member function ‘T& ref_exp<T>::data() const [with T = int]’: 
ref.cpp:17: instantiated from here 
ref.cpp:10: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’ 

但是如果我const value_type& data() const取代const_reference_type data() const它的工作原理。另外,如果我與typedef const value_type& const_reference_type替換typedef const reference_type const_reference_type
它編譯

+3

'typedef'中的'const'不會做你認爲它的作用。 –

+1

[在C++中使用typedef和模板的常量引用]的可能重複(http://stackoverflow.com/questions/3801982/constant-references-with-typedef-and-templates-in-c) – Mat

+0

它可以是一個「const (value_type&)'不同於'(const value_type)'(爲了澄清而插入大括號)? –

回答

4

const reference_type指出該參考是常量,不被引用的對象是常量。

typedef int &int_ref; // int_ref is a reference to a non-const int 
typedef const int_ref int_ref_const; 
    // int_ref_const is a const reference to a non-const int 

第二種情況下的const限定符基本上是no-op,因爲引用是隱含的const。

想想類似的情況下使用指針:

typedef int *int_ptr; // int_ptr is a pointer to a non-const int 
typedef const int_ptr int_ptr_const; 
    // int_ptr_const is a const pointer to a non-const int. 
6

const_reference_type的typedef不會做你認爲:

typedef const reference_type const_reference_type; 

const_reference_typeint& const - 也就是說,整個型reference_typeconst施加到它 - 和一個const參考不能存在,所以你得到int&。正如您期望的那樣,您沒有獲得const int&

如您所知,這裏的解決方法是要做到:

typedef const value_type& const_reference_type; 

這裏的技巧是沒有想到的typedef只是一個查找和替換類型名稱,因爲它不表現如此。

+2

這就是爲什麼我更喜歡在右側而不是左側應用const。它使得模板代碼和typedef易於閱讀。 – Nawaz

+1

@Nawaz:100%同意。這也是Alexandrescu在他的Modern C++ Design書中建議的 –

+0

@AndyProwl:在這種情況下,upvote我的回答:P – Nawaz

4

在您的typedef中,const reference_type而不是等於const value_type &,因爲您似乎認爲。這是value_type & const,這實際上是value_type &

這是我寧願在右側應用const而不是在左側應用的原因之一。如果你寫

reference_type const 

那麼它會馬上變得明顯,這是實際上此:

value_type & const //actually 

比這

value_type const & //intended 

現在很清楚,不是嗎是嗎?

請注意,value_type const &const value_type &相同類型。

總之,要解決這個問題,你需要定義的typedef爲:

typedef value_type const & const_reference_type; 

我寧願在右側申請const