我正在使用 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/