首页 > 解决方案 > 如何将 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;
}

所以基本上我想完成一些可以接收 nullptr 文字和 unique_ptr 作为函数参数的函数/API。我该怎么做?

标签: c++smart-pointersunique-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


推荐阅读