【问题标题】:How to share protected members between C++ template classes?如何在 C++ 模板类之间共享受保护的成员?
【发布时间】:2014-10-01 17:27:21
【问题描述】:

考虑以下示例:

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' 对象都能够访问彼此的受保护构造函数。有没有办法做到这一点?

【问题讨论】:

  • 你试过friendly吗?

标签: c++ templates


【解决方案1】:
template <typename T>
class ref : public _ref
{
    template <typename U>
    friend class ref;
    //...

DEMO

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 2016-04-06
  • 2020-04-13
  • 2011-04-29
  • 1970-01-01
  • 2011-03-22
相关资源
最近更新 更多