简体   繁体   English

什么是`std :: nullptr_t`模板参数的正确用例?

[英]What is a proper use-case of `std::nullptr_t` template parameters?

Today I came to know that C++ allows non-type template parameters of type std::nullptr_t : 今天我开始知道C ++允许类型为std::nullptr_t非类型模板参数:

template<std::nullptr_t N> struct A { };

template<std::nullptr_t N> void f() { } 

For the life of me, I cannot come up with any sensible use-case for these. 对于我的生活,我无法想出任何明智的用例。 Can anyone please come up with a rationale for this? 任何人都可以为此提出理由吗?

It seems this is allowed to avoid the need to special case template using a pointer type and a value for std::nullptr_t . 似乎允许使用指针类型和std::nullptr_t的值来避免使用特殊案例模板。 That, the use case would look look something like this: 那个,用例看起来像这样:

template <typename T, T Ptr>
struct pointer_object {
    static T get_pointer() { return Ptr; }
};

int int_ptr(0);

typedef pointer_object<int*, &int_ptr> int_ptr_t;
typedef pointer_object<std::nullptr_t, nullptr> null_ptr_t;

That is, pointer values can be template arguments and, thus, nullptr should be, too. 也就是说,指针值可以是模板参数,因此, nullptr应该是。

I guess it's most useful in a setting like this: 我想这在这样的设置中最有用:

template <typename T, T Value> struct Foo;

Foo<int, 10> x;
Foo<std::nullptr_t, nullptr> y;

No harm in that. 没有坏处。

(Maybe std::integral_constant is an example of this.) (也许std::integral_constant就是一个例子。)

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

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