如何在C++模板类之间共享受保护的成员

How to share protected members between C++ template classes?

本文关键字:共享 之间 受保护 成员 C++      更新时间:2023-10-16

考虑以下示例:

class _ref
{
public:
    _ref() {}
    _ref(const _ref& that) {}
    virtual ~_ref() = 0;
};
_ref::~_ref() {}
template <typename T>
class ref : public _ref
{
protected:
    ref(const _ref& that) {}
public:
    ref() {}
    ref(const ref<T>& that) {}
    virtual ~ref() {}
    template <typename U>
    ref<U> tryCast()
    {
        bool valid;
        //perform some check to make sure the conversion is valid
        if (valid)
            return ref<U>(*this); //ref<T> cannot access protected constructor declared in class ref<U>
        else
            return ref<U>();
    }
};

我希望所有类型的"ref"对象都能够访问彼此受保护的构造函数。有什么办法可以做到这一点吗?

template <typename T>
class ref : public _ref
{
    template <typename U>
    friend class ref;
    //...

DEMO