如何将NULL或nullptr传递给接收unique_ptr参数的函数


template<typename T>
void foo(T&& p1)
{
p1.get();
}
int main(int argc, char *argv[])
{
auto a = std::unique_ptr<int>();
a = NULL;

// this works because a is a unique ptr and it has a get method
foo(a);
// this does not work because NULL does not has this method. But can it work tho like how we use the raw pointer?
foo(NULL);
return 0;
}

因此,基本上我想完成一些函数/API,它可以接收nullptr-literal和unique_ptr作为函数参数。我该怎么做?

您可能会为std::nullptr_t:编写重载

void foo(std::nullptr_t) {}

并且SFINAE是第一个将其作为错误类型丢弃为int(NULL的可能类型(的形式:

template<typename T>
auto foo(T&& p1) -> decltype(p1.get(), void())
{
p1.get();
}

但使用nullptr而不是NULL

如果foo应该特别接受unique_ptr,您可以写:

template<typename ...T>
void foo(std::unique_ptr<T...>& p1)
{
p1.get();
}

关于使用NULL论点,我建议不要这样做。它是一个可以计算为int文字0std::nullptr_t类型的prvalue的宏,并且不再是用信号通知不指向有效内存的指针的首选方式。

您应该使用nullptr,然后您可以编写一个重载来匹配它:

void foo(std::nullptr_t) {}  

如果您仍然想使用NULL或以其他方式匹配任何不是unique_ptr专用化的参数,您可以添加一个与其他所有参数匹配的重载:

void foo(...) {}  

这是一个演示。

最新更新