在函数调用中,为什么nullptr不匹配指向模板对象的指针? [英] In function call, why doesn't nullptr match a pointer to a template object?
问题描述
这是一个完美运行的代码示例:
Here is an example of a code that works perfectly:
#include<iostream>
#include<vector>
template< class D, template< class D, class A > class C, class A = std::allocator< D > >
void foo( C< D, A > *bar, C< D, A > *bas ) {
std::cout << "Ok!" << std::endl;
}
int main( ) {
std::vector< int > *sample1 = nullptr;
std::vector< int > *sample2 = nullptr;
foo( sample1, sample2 );
return( 0 );
}
但是,在下面的代码中,编译器无法匹配std :: vector< int> *,第二个参数为nullptr,甚至可以从第一个参数中扣除模板类型.
In the code below, however, the compiler is unable to match std::vector< int >* with nullptr for the second parameter, even being able to deduct the template types from the first parameter.
#include<iostream>
#include<vector>
template< class D, template< class D, class A > class C, class A = std::allocator< D > >
void foo( C< D, A > *bar, C< D, A > *bas ) {
std::cout << "Ok!" << std::endl;
}
int main( ) {
std::vector< int > *sample = nullptr;
foo( sample, nullptr );
return( 0 );
}
错误消息是:
The error message is:
$ g++ -std=c++11 nullptr.cpp -o nullptr
nullptr.cpp: In function ‘int main()’:
nullptr.cpp:11:24: error: no matching function for call to ‘foo(std::vector<int>*&, std::nullptr_t)’
foo( sample, nullptr );
nullptr.cpp:11:24: note: candidate is:
nullptr.cpp:5:6: note: template<class D, template<class D, class A> class C, class A> void foo(C<D, A>*, C<D, A>*)
void foo( C< D, A > *bar, C< D, A > *bas ) {
nullptr.cpp:5:6: note: template argument deduction/substitution failed:
nullptr.cpp:11:24: note: mismatched types ‘C<D, A>*’ and ‘std::nullptr_t’
foo( sample, nullptr );
为什么会这样?
Why does that happen?
推荐答案
来自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)
.
这篇关于在函数调用中,为什么nullptr不匹配指向模板对象的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!