【问题标题】:Custom "nullptr", but how to understand the codes?自定义“nullptr”,但如何理解代码?
【发布时间】:2017-04-01 02:27:06
【问题描述】:

来自维基百科,如果我们的编译器不支持c++11,我们可以自己实现一个,如下所示:

const class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }

private:
    void operator&() const;
} nullptr = {};

上面的代码我看不懂。

----------更新------

对不起,我没有表达清楚。

 template<class T>
    inline operator T*() const
        { return 0; }

 template<class C, class T>
    inline operator T C::*() const
        { return 0; }

以上代码,我不懂语法。 我以前从未见过这种模板形式。(如“operator T C::*()”)

【问题讨论】:

  • 哪部分不明白?
  • 代码定义了一个名为nullptrconst 变量nullptr_t。 2 个隐式转换运算符允许 nullptr 在任何可以使用指针的地方使用。

标签: c++ c++11 templates nullptr


【解决方案1】:
template<class T>
inline operator T*() const
    { return 0; }

表示nullptr_t 类型的对象可以隐式转换为任何(非成员)指针类型。它只是一个为任何类型T 模板化的operator T *() 函数(转换为T * 类型)。

template<class C, class T>
inline operator T C::*() const
    { return 0; }

表示nullptr_t 类型的对象可以转换为指向任何类型(模板参数T)的任何类(模板参数C)的非静态成员的指针。

两个运算符都是const,因此无法更改nullptr_t 对象。

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2023-02-04
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多