簡體   English   中英

如何在C ++模板類之間共享受保護的成員?

[英]How to share protected members between C++ template classes?

請考慮以下示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM