2013-01-20 19 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