强制转换 boost::shared_array; boost::shared_array;
如何将 boost::shared_array
转换为 boost::shared_array
?
How can I cast a boost::shared_array<char>
to boost::shared_array<const char>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
由于
shared_array
没有add_ref
方法,您可以按如下方式模拟它:Since
shared_array
has noadd_ref
method you could emulate it as follows:其他答案都是正确的,你不能也不应该。
此外,您确定需要
boost::shared_array
而不是const boost::shared_array
吗?实际上,这是可行的:
但这不是一个好主意,并且只有在 boost::shared_array 和 boost::shared_array 具有相同的实现时才有效。模板可以部分专用:
在
TwoImplementations
和TwoImplementations
之间进行重新解释是错误的。The other answers are correct, you can't and you shouldn't.
Besides, are you sure you want a
boost::shared_array<const char>
and not aconst boost::shared_array<char>
?Practically, this works:
BUT it is not a good idea and only works if boost::shared_array and boost::shared_array have the same implementation. Templates can be partially specialized:
Doing a reinterpret cast between
TwoImplementations<int>
andTwoImplementations<const int>
is just wrong.你不能。
由于这两种类型都基于模板,因此对于编译器来说这两种类型完全不同。
You can't.
As both types are based on a template, both types are completely different for the compiler.
我认为你不能。如果您确实需要它,您可以创建一个自定义智能指针类。可以在此处找到相关提示。
I think you can't. In case you really need it though, you can create a custom smart-pointer class. Hints for that can be found here.
您可以使用 get() 方法获取底层 char*,它可以自动转换为 const char* - 但不要将其分配给另一个共享数组,因为那样您将删除数据两次。只需根据需要使用即可。
像这样:
You could use the get() method to get the underlying char*, which is auto convertible to a const char* - but don't assign it to another shared_array because then you'll have the data deleted twice. Just use it as you need it.
like this:
如果没有 Kirill 的精彩回答,我不会想到这一点,但是您可以有效地将用于
shared_ptr
的 boost 的static_pointer_cast
扩展为在shared_array
上工作> 就是这样:这样你就可以做类似的事情:
I wouldn't have thought of this without Kirill's awesome answer, but you can effectively extend boost's
static_pointer_cast
that is used forshared_ptr
s to work onshared_array
s as so:with that you can then do something like:
这种由编译器生成的转换是不可能的。
由于模板专门化功能,具有 const 限定模板参数的类的内部结构可能与不具有 const 限定模板参数的类有很大不同。
此外,这种功能的使用有时是编译时检查的背景,编译时检查可能不允许在
A
的每种情况下实例化A
类型。 > 类型正确。Such compiler-generated casting can not be possible.
The internals of the class with const-qualified template parameter may differ dramatically from the class without one, due to template specialization feature.
Moreover, the use of such feature is sometimes a background for compile-time checks that merely may not allow instantiation of
A<const T>
type for every case whereA<T>
type is correct.