Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

Consider the following example:

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>();
    }
};

I would like all types of 'ref' objects to be able to access each other's protected constructors. Is there any way to accomplish this?

like image 256
Madison Brown Avatar asked Oct 01 '14 17:10

Madison Brown


1 Answers

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

DEMO

like image 166
Piotr Skotnicki Avatar answered Nov 14 '22 21:11

Piotr Skotnicki