c++ - 变量模板参数中的decltype

标签 c++ c++11

我正在使用 unique_ptr 编写一些代码s之类的。该行是:

std::unique_ptr<char[], void(*)(void*)> result(..., std::free);

哪个有效。我意识到 std::free 给出的类型是第二个模板参数。我尝试使用:

std::unique_ptr<char[], decltype(std::free)> result(..., std::free);

这会更容易阅读并且更不容易出错。但是我收到与 <memory> 相关的错误和“用函数类型实例化数据成员”。

有没有办法做到这一点?

最佳答案

decltype(std::free) 产生std::free 的类型,即函数类型void(void*) ,而不是函数指针类型 void(*)(void*)。您需要一个函数指针类型,您可以通过获取 std::free 的地址来获得它:

std::unique_ptr<char[], decltype(&std::free)> result(..., std::free);
                               ^

或者通过自己构造函数指针类型:

std::unique_ptr<char[], decltype(std::free)*> result(..., std::free);
                                         ^

(我认为前者更清楚。)

关于c++ - 变量模板参数中的decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820212/

相关文章:

c++ - 我如何从将 C++ 理解为一种语言跳转到理解职位发布的所有首字母缩略词

c++ - 在此代码示例中,.push() 是在锁定时失败还是等待?

c++ - 将原子变量传递给函数

c++ - std::atomic_compare_exchange_* 等如何与任意指针一起使用?

c++ - 如何从 multimap 中删除特定的重复项?

c++ - 向类中添加新成员变量会影响二进制兼容性吗?

c++ - boost 找不到文件

c++ - TCP没有收到发送的数据

C++ 正确的新用法?

c++ - 是否可以优雅地在 vector<MyType> 上运行标准算法?