c++ - 如何将 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。我该怎么做?
解决方案
您可能会为 编写重载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
推荐阅读
- python - 有没有办法在 opencv-python 中显示最后一帧?
- python-3.x - 使用 BeautifulSoup 抓取网页中的 URL
- html - 在 ReactNative View 上设置 flex body 的高度 100%
- r - R中seq(1,5)与seq(1:5)之间的区别
- php - 如何在php中将数字的值转换为字符串?
- python - 有没有办法检查以数字开头的文件名?
- aws-lambda - 为 aws-lambda 开发组织 PyCharm 项目
- c++ - 我正在尝试使用此代码查找二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- azure-sql-server - Azure Sql Server 管理员登录名有哪些限制?
- javascript - 基于 img src 路径下载图像并将其转换为 JavaScript 中的 File 对象或 Blob