首页 > C++ 嵌套typedef的问题

C++ 嵌套typedef的问题

最近在写一个Tiny的STL库。可是出现了一点小问题。

如果一个typedef使用已定义过的typedef,如下列代码的
using value_type = T;
using reference = value_type&;
using const_reference = const reference;

template <typename T>
class allocator
{
public:
    using value_type      = T;
    using pointer         = value_type*;
    using const_pointer   = const pointer;
    using reference       = value_type&;
    using const_reference = const reference;
    using size_type       = std::size_t;
    using difference_type = std::ptrdiff_t;    
...

    const_pointer address(const_reference x) { return static_cast<const_pointer>(&x); }
...
};

但是编译时会出现以下问题:

其中61 行就是上面的address函数。
如果我把typedef 改为以下形式,

using value_type      = T;
using pointer         = T*;
using const_pointer   = const T*;
using reference       = T&;
using const_reference = const T&;
using size_type       = std::size_t;
using difference_type = std::ptrdiff_t;

编译报以下错误:

请问,
1、这两种定义方式都可以吗?如果可以,上述两种不同的报错方式该如何解释?
2、第二张图里的error该如何解决?

源代码太多,不大方便粘贴上来。
参见:https://github.com/MarinYoung4596/MySTL/tree/master/MySTL/MySTL

google了好久也没找到原因,因此也不知道该如何解答。
烦请大神们答疑解惑。

亦或者,能否告知这些错误可能是由于什么原因造成的?(或者我哪一块的语法理解不透彻),以便我查漏补缺?
非常感谢!


首先纠正两处错误:

using value_type      = T;
using pointer         = value_type*;
using const_pointer   = const pointer;
using reference       = value_type&;
using const_reference = const reference;
using size_type       = std::size_t;
using difference_type = std::ptrdiff_t;    

const_pointer
== const pointer
== pointer const
== value_type* const
!= value_type const * // 这才是你要的
const_reference同理。

手上没有2015,我是用2013编译的。在去掉了2013不存在的noexcept之后,我还发现你的test_vector.cpp里面的
myvector.insert(it, 2, 300)
实际上调用的是这个版本:

template<typename InputIterator>
iterator insert(iterator position, InputIterator first, InputIterator second);

然后就出翔了。构造函数和assign函数也有类似的错误。

其实这很好理解,2和300类型一样,为什么要去匹配那个size_type和const_reference的,C++的重载不是按照声明顺序的。

所有的错误都是归结到这两个地方。因为我让十几行这样的代码强制对应到你想要的那个重载之后,我发现编译过了。不过我没有运行,因为这不是题目要求的范围,哈哈哈哈。

【热门文章】
【热门文章】