【发布时间】:2016-07-31 08:14:50
【问题描述】:
以下是实现共享指针的尝试,修改后的语义为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) 抱怨无效转换。为什么它不起作用,我应该怎么做而不是这个演员?
【问题讨论】:
-
使用
friend。这不是罪。 -
@n.m.您的意思是有一个带有
std::shared_ptr参数的私有构造函数吗? -
抱歉,没有仔细看你的代码。仅当派生类型具有采用父类型的构造函数,或者父类型具有正确的类型转换运算符时,才能强制转换为派生类型(不是指针)。所以是的,你确实需要一个构造函数。是否将其设为私有取决于您,
-
@n.m.这使得下面的答案错了,不是吗?
-
看起来是的,是的。
标签: c++ inheritance private-inheritance