元组可与nullptr一起使用,但不适用于NULL

Sat*_*h D 2 c++ tuples

我有以下代码,其中std :: tuple可与nullptr一起使用,但不适用于NULL。

#include <iostream>
#include <tuple>

int main()
{
tuple<int*> t1, t2;

t1 = std::make_tuple(NULL);
t2 = std::make_tuple(nullptr);
}
Run Code Online (Sandbox Code Playgroud)

当使用C ++ 11编译时,该代码在使用nullptr时有效,但是在使用NULL的情况下会出现以下错误。

In file included from tuple.cpp:2:
/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/tuple:447:8: error: assigning to 'int *' from incompatible type 'long'
            = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in));
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/tuple:575:36: note: in instantiation of function template specialization 'std::_Tuple_impl<0, int *>::operator=<long>' requested here
          static_cast<_Inherited&>(*this) = std::move(__in);
                                          ^
tuple.cpp:13:8: note: in instantiation of function template specialization 'std::tuple<int *>::operator=<long, void>' requested here
    t1 = std::make_tuple(NULL);
       ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

在这里,NULL的类型是long int,并且元组足够严格并且不接受它。

我们如何使它也可以使用NULL来工作,正如我们的客户所说的那样,当与nvcc编译器一起使用时(当他们在CUDA代码中使用上述代码片段时)它可以工作,但否则无法工作。

eer*_*ika 5

我们如何也可以使用NULL使其工作

您可以使用std::make_tuple<int*>(NULL)std::tuple<int*>(NULL)。但更喜欢使用nullptr

您面临的问题是nullptr被引入该语言的原因。在其引入之前,唯一的标准空指针文字是0(0L等也是有效的),也就是NULL1扩展为的内容。

问题在于0不仅是指针文字,而且实际上是整数文字。字面量的整数性质优先于模板类型实参推导,并且std::make_tuple(NULL)可能导致std::tuple<int>std::tuple<long>取决于的确切定义NULL。而且这些元组不能隐式转换为std::tuple<int*>


1从技术上讲,现在nullptr该语言NULL也可以扩展到该语言。但这不太可能发生。

  • 他们几年前在MSVS的库代码库中尝试了“ #define NULL nullptr”,编译器爆炸了。不幸的是,对NULL的错误使用已广为流传。 (3认同)