使std :: unique <T>与std :: unique <const T,CustomDeleterType>兼容

And*_*y R 4 c++ c++11

在代码中,我为特定对象定义了3个std :: unique_ptr指针类型:

typedef std::unique_ptr<MyObject> nonConstPtrDefaultDelete;

typedef std::unique_ptr<MyObject, std::function<void(MyObject *)>>
                                                       nonConstPtrCustomDelete;

typedef std::unique_ptr<const MyObject, std::function<void(const MyObject *)>>
                                                       ConstPtrCustomDelete;
Run Code Online (Sandbox Code Playgroud)

我遇到了一个用例,我需要将nonConstPtrDefaultDelete转换为ConstPtrCustomDelete,将nonConstPtrCustomDelete转换为ConstPtrCustomDelete.换一种说法:

nonConstPtrDefaultDelete a;
nonConstPtrCustomDelete b;

ConstPtrCustomDelete c1(a);  // Compiler error Deleter has incompatible type
ConstPtrCustomDelete c2(b);  // Compiler error Deleter has incompatible type
Run Code Online (Sandbox Code Playgroud)

主要问题来自删除功能的类型签名的不兼容性.可以通过以下方式更改nonConstPtrCustomDelete类型的定义来修复nonConstPtrCustomDelete案例:

typedef std::unique_ptr<MyObject, std::function<void(const MyObject *)>>
                                                         nonConstPtrCustomDelete
Run Code Online (Sandbox Code Playgroud)

但是,最常见的DefaultDelete情况仍然会产生编译错误,尽管很明显可以进行转换.它有一种解决方法,限制并提示编译器的功能可以从一个转换为另一个?

谢谢

Sla*_*ica 6

如果您确定删除器是正确的,您可以将DefaultDelete转换为您的类型:

nonConstPtrDefaultDelete a;
ConstPtrCustomDelete c1( a.release(), your_deleter );
Run Code Online (Sandbox Code Playgroud)

与const/non const版本相同.但是为什么你需要2个版本(一个用于const而一个用于not)尚不清楚.