search

Home  >  Q&A  >  body text

c++11 - 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了好久也没找到原因,因此也不知道该如何解答。
烦请大神们答疑解惑。

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

大家讲道理大家讲道理2806 days ago792

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 13:13:44

    First correct two errors:

    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 * // This is what you want
    const_reference Same reason.

    I don’t have 2015 at hand, I compiled it with 2013. After removing noexcept that does not exist in 2013, I also found that
    myvector.insert(it, 2, 300)
    in your test_vector.cpp actually calls this version:

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

    Then it took off. There are similar errors with constructors and assign functions.

    In fact, this is easy to understand. The 2 and 300 types are the same. Why should we match the size_type and const_reference? The overloading of C++ is not in the order of declaration.

    All errors are attributed to these two places. Because after I forced a dozen lines of code like this to correspond to the overload you want, I found that it was compiled. But I didn’t run it because it was not within the scope of the question, hahahaha.

    reply
    0
  • Cancelreply