Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

Today I came to know that C++ allows non-type template parameters of type 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?

like image 395
Johannes Schaub - litb Avatar asked Dec 02 '12 00:12

Johannes Schaub - litb


People also ask

Why do we use :: template template parameter?

Correct Option: D. It is used to adapt a policy into binary ones.

Which is a correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.

How do you use template arguments in C++?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is the role of parameter in a template?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


2 Answers

It seems this is allowed to avoid the need to special case template using a pointer type and a value for 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.

like image 86
Dietmar Kühl Avatar answered Oct 04 '22 11:10

Dietmar Kühl


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.)

like image 36
Kerrek SB Avatar answered Oct 04 '22 09:10

Kerrek SB