先指示以下代码:
class Reference : public std::enable_shared_from_this<Reference> {
public:
inline Reference() noexcept
: enable_shared_from_this() {
}
public:
inline std::shared_ptr<Reference> GetReference() const noexcept {
return const_cast<Reference*>(this)->shared_from_this();
}
};
class IDisposable : public Reference {
public:
virtual void Dispose() = 0;
};
class MyClass : public IDisposable {
public:
virtual void Dispose() noexcept override;
};
上述代码看上去是非常正常的,那么我们通过 Reference::GetReference() 可以获取到 std::shared_ptr<Reference> 的共享引用指针。
实例则为:MyClass*
那么是否可以让 “std::shared_ptr<Reference>” 转换为 “std::shared_ptr<MyClass>” 的共享引用指针呢?
答案是可以的,但是存在非常多的限制,人们需要确保编译器打开 FULL RTTI on C/C++ 编译器反射特性,局部 RTTI 无法支持多重泛型模板元类型的逆变。
template<typename _Ty1, typename _Ty2>
inline static std::shared_ptr<_Ty1> AsReference(const std::shared_ptr<_Ty2>& v) noexcept {
return v ? std::dynamic_pointer_cast<_Ty1>(v) : NULL;
}
C/C++ 标准库中提供了 “std::dynamic_pointer_cast<_Ty1, _Ty2>(const _Ty2& pointer)” 的模板函数,内部实现基于 dynamic_cast<_Ty1>(_Ty2*) 关键字(语法糖)通过检查类示例的继承表(需要 FULL RTTI+)来实现转换,大多数情况下,未调整RTTI编译器选项的情况下,默认不是FULL RTTI+,这会导致 C/C++ 逆变类型编译失败,其实:Reference* 指向的是 MyClass*。
此时,人们只得寻求较为危险不安全的方法来实现 Reference* 逆变为 MyClass*,目前大家采取得办法为 “static_cast<MyClass*>(Reference*)”,那么为什么不适用 “(MyClass*)(MyClass*)”?问出这种问题得家伙,C/C++ 这块需要回炉重造一下了。
一个简单的问题,如果 Reference* 指向 NULL,人们采用 stack_cast<MyClass*>(...) 后得 MyClass* 地址标识符,仍旧指向 NULL?
public:
template<typename _Ty1, typename _Ty2>
inline static std::shared_ptr<_Ty1> CastReference(const std::shared_ptr<_Ty2>& v) noexcept {
if (!v) {
return NULL;
}
_Ty2* native_pTy2 = const_cast<_Ty2*>(v.get());
_Ty1* native_pTy1 = static_cast<_Ty1*>(native_pTy2);
const std::shared_ptr<_Ty2> shared_pTy2 = v;
return std::shared_ptr<_Ty1>(native_pTy1, [shared_pTy2](const void*) noexcept {});
}
上述代码可以实现多重类型得 “逆变”,但人们需要在编译期间确保逆变泛型模板元类型是可靠的,因为这种操作是不安全的,但通常不会,如果人们大量得进行 “逆变” 类型,那么这违背大量的编程设计原则,直接跟多个类型耦合,起不到依赖导致的作用。