如何在C ++模板类之间共享受保护的成员? [英] How to share protected members between C++ template classes?

查看:82
本文介绍了如何在C ++模板类之间共享受保护的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

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'对象能够访问彼此的受保护的构造函数。是否有任何方法可以实现这一点?

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?

推荐答案

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

DEMO

这篇关于如何在C ++模板类之间共享受保护的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆