以下尝试使用修改后的operator==
语义实现共享指针:
template <typename T>
struct deref_shared_ptr: private std::shared_ptr<T> {
using Base = std::shared_ptr<T>;
// ... using statements to include functionality from the base.
bool operator==(const deref_shared_ptr rhs) const {
return (**this == *rhs);
}
};
我正在努力为这种类型实现一个等效的 std::make_shared
。这是我的尝试:
template< class T, class... Args >
deref_shared_ptr<T> make_deref_shared( Args&&... args ) {
return reinterpret_cast<deref_shared_ptr<T>>(std::make_shared<T>(args...));
}
这不起作用:编译器 (g++ 5.4.0
) 提示转换无效。为什么它不起作用,我应该怎么做而不是这个 Actor ?
最佳答案
您看到此编译器错误消息是因为 reinterpret_cast
无法通过私有(private)继承进行转换。请检查有关此主题的以下主题:difference between c++ casts , conversion which may be handled by c-style cast only .
通过 private
继承的唯一方法是 c 风格的转换。因此,按如下方式更改您的示例会使您的示例有效:
template< class T, class... Args >
deref_shared_ptr<T> make_deref_shared(Args&&... args) {
return (deref_shared_ptr<T>)(std::make_shared<T>(args...));
}
C 风格的转换在一般情况下是不安全的,因为它在多重继承和其他一些情况下可能无法正常工作,但 AFAIK 在这种情况下是安全的。
关于c++ - 如何转换为私有(private)派生的子类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682050/