C++“强制构造函数”无法访问私有成员

tjw*_*992 5 c++ templates coercion copy-constructor private-members

我正在尝试编写一些使用“成员模板强制”模式的代码,以便创建一个可以保存指向多种类型的指针并以多态方式处理它们的容器。

我在尝试编写“强制构造函数”时遇到了问题?(我不确定你真正会怎么称呼它),但是我的代码无法编译,说明我无法访问该类的私有成员。

常规复制构造函数工作正常并且确实具有访问权限,但由于某种原因使用不同的模板类型突然导致它失去访问权限。

#include <boost/shared_ptr.hpp>

template <typename T>
class Container {
public:
    Container<T>(T* contents) : m_contents(contents) {}

    // Copy constructor
    Container<T>(const Container<T>& other) : m_contents(other.m_contents) {}

    // Coercion constructor?
    template <typename U>
    Container<T>(const Container<U>& other) : m_contents(other.m_contents) {}

    T* get_contents() {
        return m_contents;
    }

private:
    T* m_contents;
};

// Things for the container to hold
struct A {};
struct B : public A {};

int main() {
    B* object1 = new B;
    Container<B> container1(object1);

    // Works fine
    Container<B> container2(container1);

    // Fails to compile because m_contents is private....
    Container<A> container3(container1);
}
Run Code Online (Sandbox Code Playgroud)

如何在不公开的情况下访问“强制构造函数”中的成员变量?公开它会破坏封装并破坏容器的整个目的。

另外,添加“get_contents()”方法并在“强制构造函数”中使用它也不是一个选项,因为我不希望从外部访问内容。