简体   繁体   English

Null 类型在标准 C++ 库中

[英]Null type in standard C++ library

Is there some special null type and value in standard C++ library, eg defined as struct null_type_t {};标准 C++ 库中是否有一些特殊的 null 类型和值,例如定义为struct null_type_t {}; ? ?

I want to use it in different places to signify that there is no value passed.我想在不同的地方使用它来表示没有传递任何值。

Eg to use in next template:例如在下一个模板中使用:

template <typename T = std::null_type_t>
struct S {};

Or in structure like next:或者像下一个这样的结构:

template <typename T>
struct Optional {
    constexpr Optional() = delete;
    constexpr Optional(std::null_type_t) {}
    template <typename OT>
    constexpr Optional(OT const & val)
        : has_value(true), value(val) {}
    bool const has_value = false;
    T const value = T();
};

Basically if std::null_type_t type or value is passed as template or function parameter then my code will do some special handling, ie this null type signifies that there is no value.基本上如果std::null_type_t类型或值作为模板或 function 参数传递,那么我的代码将做一些特殊处理,即这个 null 类型表示没有值。

Of cause I can define in my code my own struct like next:当然,我可以在我的代码中定义我自己的结构,如下所示:

struct NullType {};

But I did this kind of definition in code many times already.但是我已经在代码中多次做了这种定义。 And maybe there exists special standard library type for this kind of thing, which I can use everywhere instead of my definition of null struct.也许这种东西存在特殊的标准库类型,我可以在任何地方使用它,而不是我对 null 结构的定义。

There is nullptr_t type and nullptr value, that I can use in some places.nullptr_t类型和nullptr值,我可以在某些地方使用。 But not all, because if function or template parameter is a pointer type then sometimes I want to pass null pointer to signify real value of null pointer, not the absence of value.但不是全部,因为如果 function 或模板参数是指针类型,那么有时我想传递 null 指针来表示 null 指针的实际值,而不是缺少值。 That's why for such pointer-typed cases would be good to have some separate type like struct null_type_t {};这就是为什么对于这种指针类型的情况,最好有一些单独的类型,比如struct null_type_t {}; which doesn't interfere with pointer or any other class or built-in type.它不会干扰指针或任何其他 class 或内置类型。

std::optional uses std::nullopt_t for this purpose: https://en.cppreference.com/w/cpp/utility/optional/nullopt_t std::optional为此目的使用std::nullopt_thttps://en.cppreference.com/w/cpp/utility/optional/nullopt_t

So for your own optional type, you should probably implement your own nullopt_t .因此,对于您自己的可选类型,您可能应该实现自己的nullopt_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM