[英]Can nullptr be used as a type?
I was learning about the usage of enable_if
and I stumbled upon the following code. 我正在学习
enable_if
的用法,偶然发现了以下代码。
template <class T,
typename std::enable_if<std::is_integral<T>::value,
T>::type* = nullptr>
void do_stuff(T& t) {
std::cout << "do_stuff integral\n";
// an implementation for integral types (int, char, unsigned, etc.)
}
The thing that bothers me is that in the template parameter, nullptr is used as a default parameter to the std::enable_if<std::is_integral<T>::value, T>::type*
which is also a type. 困扰我的是,在模板参数中,nullptr用作
std::enable_if<std::is_integral<T>::value, T>::type*
的默认参数,这也是一种类型。
I am not sure how we can assign a literal to the type. 我不确定如何为该类型分配文字。 Shouldn't it be
nullptr_t
instead? 应该不是
nullptr_t
吗?
This template accept a non-type second parameter, that is a pointer typename std::enable_if<std::is_integral<T>::value, T>::type *
so nullptr
is used as default value for this pointer. 该模板接受非类型的第二个参数,即指针
typename std::enable_if<std::is_integral<T>::value, T>::type *
因此nullptr
用作此指针的默认值。 Note that typename
in this second parameter is used to make compiler figure out that ::type
as a type, it is not a beginning of usual type template parameter like typename T
请注意,第二个参数中的
typename
用于使编译器确定::type
为类型,而不是像typename T
这样的普通类型模板参数的开头
nullptr
is not a type, it's a value (of type nullptr_t
, which can be converted to any pointer type IIRC). nullptr
不是类型,而是一个值(类型为nullptr_t
,可以将其转换为任何IIRC指针类型)。 Otherwise, any standard usage of nullptr
like: 否则,
nullptr
任何标准用法如下:
int* a = nullptr;
would not work. 将无法正常工作。
This is an unnamed default template parameter used to allow SFINAE in a template declaration instead of using the return type. 这是一个未命名的默认模板参数,用于允许在模板声明中使用SFINAE,而不使用返回类型。 It's basically like:
基本上就像:
template<int=0>
void foo();
With the SFINAE trick/ enable_if
. 使用SFINAErick /
enable_if
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.