[英]Why isn't it necessary to specialize for `std::nullptr_t` if there's a specialized function AND a templated function
Consider the following code: 请考虑以下代码:
#include <iostream>
using namespace std;
void fun(const char* s){
if (s == nullptr) {
puts("const char* nullptr");
} else {
printf("%s\n", s);
}
}
template <typename T>
void fun(T* p){
printf("%p\n", p);
}
int main() {
int a;
fun("abc"); // Resolves to fun(const char*)
fun(&a); // Specializes the template to int*
fun(nullptr); // Uses fun(const char*)??
fun(NULL); // Same as above
}
I'm surprised that g++ 7.2.0
does not throw an error about ambiguous overload resolution, as I think nullptr
and NULL
could fit into any pointer type, including fun(int*)
specialized from the template, provided there isn't an overload specialized for std::nullptr_t
. 我很惊讶
g++ 7.2.0
没有抛出关于模糊重载g++ 7.2.0
的错误,因为我认为nullptr
和NULL
可以适合任何指针类型,包括模板专用的fun(int*)
,前提是没有重载专门用于std::nullptr_t
。
Why does fun(nullptr)
and fun(NULL)
resolves directly to fun(const char *)
? 为什么
fun(nullptr)
和fun(NULL)
直接解析为fun(const char *)
?
std::nullptr_t
is not a pointer, so it will not pattern-match T*
in your function template. std::nullptr_t
不是指针,因此它不会在函数模板中与T*
进行模式匹配。
As counter-intuitive as this is, the following assert will not fire: 由于这是违反直觉的,因此以下断言不会触发:
static_assert(std::is_pointer<std::nullptr_t>() == false);
As for NULL
, it is an implementation-defined macro. 至于
NULL
,它是一个实现定义的宏。 If cppreference is to be believed, it's either an integer literal with value of zero (so not a pointer), or a prvalue of type std::nullptr_t
, which is explained above. 如果要相信cppreference,它可以是值为零的整数文字(因此不是指针),也可以是
std::nullptr_t
类型的prvalue,如上所述。 It is not a void*
pointer. 它不是
void*
指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.