且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在函数调用中,为什么nullptr不匹配指向模板对象的指针?

更新时间:2023-11-13 09:44:40

来自C ++标准(4.10指针转换[conv.ptr])

From the C++ standard (4.10 Pointer conversions [conv.ptr])

1空指针常量是整数类型的整数常量表达式(5.19)prvalue 其值为零或类型为std :: nullptr_t的prvalue.空指针常量可以是 转换为指针类型;结果是该类型的空指针值,并且是 可以与对象指针或函数指针类型的所有其他值区分开.这样的 转换称为空指针转换.

1 A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion.

在您的第一个示例中,您的两个nullptr在转换模板参数之前已被转换.因此,您有两次相同的类型是没有问题的.

In your first exemple your two nullptr have already been converted before template argument deduction. So there is no problem you have the same type twice.

在第二个中,有一个std::vector<int>std::nullptr_t,并且不匹配.您必须自己进行转换:static_cast<std::vector<int>*>(nullptr).

In the second one, there is a std::vector<int> and a std::nullptr_t and that does not match. You have to do the conversion yourself: static_cast<std::vector<int>*>(nullptr).