我試圖實現一個std::unique_ptr
工廠,我可以用這樣的:包裝打造的std ::的unique_ptr與普通函數刪除器
auto fd = my_make_unique<fclose>(fopen("filename", "r"));
即,通過刪除器功能作爲一個模板參數。
我在C++ 11最好的嘗試是:
template<typename D, D deleter, typename P>
struct Deleter {
void operator()(P* ptr) {
deleter(ptr);
}
};
template<typename D, D deleter, typename P>
std::unique_ptr<P, Deleter<D, deleter, P>> my_make_unique(P* ptr)
{
return std::unique_ptr<P, Deleter<D, deleter, P>>(ptr);
}
在C++ 14它是乾淨多了:
template<typename D, D deleter, typename P>
auto my_make_unique(P* ptr)
{
struct Deleter {
void operator()(P* ptr) {
deleter(ptr);
}
};
return std::unique_ptr<P, Deleter>(ptr);
}
但兩者solutuions需要我傳球的&fclose
類型之前fclose
本身作爲模板參數:
auto fd = my_make_unique<decltype(&fclose), fclose>(fopen("filename", "r"));
是否有可能擺脫decltype(&fclose)
C++ 11中的模板參數?在C++ 14中怎麼樣?
編輯:爲什麼這個問題不是RAII and smart pointers in C++的重複:引用的問題是關於C++中的一般RAII技術,並且其中一個答案可以用於此目的。我已經熟悉RAII模式,以及std::unique_ptr
是如何解決的,但我關心的是如何在與C庫交互時遇到的這種常見情況下構建更易於使用的抽象。
'FILE *'只是大家熟悉的一個例子。這對於與充滿'create_()'和'destroy_ ()'函數的C庫進行交互最有用。無論如何,'*'和' - >'也可用於普通的'FILE *'指針,並且它在'std :: unique_ptr'中也不會更糟。 –
lvella
@Ivella參見http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c特別是[this](http://stackoverflow.com/a/395168/8877)回答哪些區別內存和任意資源之間。 –
我不同意這個重複標記,我的問題更具體。 – lvella