c++ - 如何转换为私有(private)派生的子类型?

标签 c++ inheritance private-inheritance

以下尝试使用修改后的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/

相关文章:

c++ - 为什么 long 在查找三个整数的第二大时显示错误输出?

c++ - 在以下情况下纹理是如何被破坏的?

python - 继承烦恼。 - Python

c# - 没有从派生到基础类的装箱转换

c++ - CGAL 在 3D 中按 x 轴旋转

c++ - C++ 中是否自动声明内部函数?

c++ - 使用 protected C++ 防止派生类的继承

编译器可以删除 C++(虚拟)私有(private)基类吗?

c++ - 为什么 Visual Studio 编译器在此示例中允许违反私有(private)继承?

c++ - 私有(private)继承和交换