提问者:小点点

如何将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文本和unique_ptr作为函数参数。我怎么能做到呢?


共2个答案

匿名用户

您可以为std::nullptr_t编写重载:

void foo(std::nullptr_t) {}

和SFINAE的第一个形式,因为类型错误而将其丢弃为int(可能为null):

template<typename T>
void 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();
}

然后添加一个捕获所有其他内容的重载:

void foo(...) {}  // called for NULL or nullptr argument

这是一个演示。