gpt4 book ai didi

c++ - 如果有专门的函数和模板函数,为什么没有必要专门针对 `std::nullptr_t`

转载 作者:太空狗 更新时间:2023-10-29 20:34:26 26 4
gpt4 key购买 nike

考虑以下代码:

#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
}

我很惊讶 g++ 7.2.0 确实没有抛出关于模糊重载解析的错误,正如我认为的 nullptrNULL 可以适合任何指针类型,包括从模板专门化的fun(int*),前提是没有专门用于 的重载std::nullptr_t.

为什么 fun(nullptr)fun(NULL) 直接解析为 fun(const char *)

最佳答案

std::nullptr_t 不是指针,因此它不会在您的函数模板中与 T* 进行模式匹配。

尽管这是违反直觉的,但以下断言不会触发:

static_assert(std::is_pointer<std::nullptr_t>() == false);

至于NULL ,它是一个实现定义的宏。如果要相信 cppreference,它要么是值为零的整数文字(因此不是指针),要么是 std::nullptr_t 类型的纯右值,这在上面已经解释过了。它不是 void* 指针。

关于c++ - 如果有专门的函数和模板函数,为什么没有必要专门针对 `std::nullptr_t`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48578085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com