变量模板参数中的Decltype

use*_*973 4 c++ c++11

我正在使用unique_ptrs 等处理一些代码.这条线是:

std::unique_ptr<char[], void(*)(void*)> result(..., std::free);
Run Code Online (Sandbox Code Playgroud)

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

std::unique_ptr<char[], decltype(std::free)> result(..., std::free);
Run Code Online (Sandbox Code Playgroud)

这将更容易阅读,更容易出错.但是我得到了<memory>与"使用函数类型实例化数据成员" 相关的错误.

有没有办法做到这一点?

Jam*_*lis 12

decltype(std::free)产生类型std::free,即函数类型void(void*),而不是函数指针类型void(*)(void*).你需要一个函数指针类型,你可以通过以下地址获得std::free:

std::unique_ptr<char[], decltype(&std::free)> result(..., std::free);
                               ^
Run Code Online (Sandbox Code Playgroud)

或者通过自己形成函数指针类型:

std::unique_ptr<char[], decltype(std::free)*> result(..., std::free);
                                         ^
Run Code Online (Sandbox Code Playgroud)

(我认为前者更清楚.)