c++ - Friend class not able to access private data -
here class declaration:
template <class t> class sptr { template<typename u> friend class sptr; template <typename t1, typename t2> friend bool operator==(const sptr<t1> &a, const sptr<t2> &b); template <typename u> friend sptr<t> static_pointer_cast(const sptr<u> &sp); private: rc* ref; //reference counter t* obj;//pointer current obj std::function<void()> destroydata; bool ok_; public: sptr(); ~sptr(); template <typename u> sptr(u *); sptr(const sptr &); template <typename u> sptr(const sptr<u> &); template <typename u> sptr<t> &operator=(const sptr<u> &); sptr<t> &operator=(const sptr<t> &); void reset(); t* operator->() const {return obj;}; t& operator*() const {return *obj;}; t* get() const {return obj;}; explicit operator bool() const { return ok_; } };
below code thats complaining of access problem
template <typename t, typename u> sptr<t> static_pointer_cast(const sptr<u> &sp) { //do sptr<u> answer; answer.obj = sp.obj; answer.ref = sp.ref; answer.destroydata = sp.destroydata; answer.ok_ = sp.ok_; return answer; }
when compile following code:
sptr<derived> sp(new derived); sptr<base1> sp2(sp); // sptr<derived> sp3(sp2); // should give syntax error. sptr<derived> sp3(static_pointer_cast<derived>(sp2)); // sptr<derived> sp4(dynamic_pointer_cast<derived>(sp2)); // should give syntax error polymorphism.
i have made friend function. why not able access variables , how correct it?
this bit tricky. code compiles if replace
template <typename u> friend sptr<t> static_pointer_cast(const sptr<u> &sp);
with
template <typename t1, typename t2> friend sptr<t1> static_pointer_cast(const sptr<t2> &sp);
the reason following (i not 100% sure, please approve / dis-approve):
when sptr<t>
instantiated, e.g. t = derived
, resulting class definition (sptr<derived>
) defines friend function having following signature:
template <typename u> friend sptr<derived> static_pointer_cast(const sptr<u> &sp);
so function has one template parameter. function defined has two template parameters.
your call templated function specialization looks this:
sptr<derived> static_pointer_cast(const sptr<base1> &sp) { //do sptr<derived> answer; answer.obj = sp.obj; answer.ref = sp.ref; answer.destroydata = sp.destroydata; answer.ok_ = sp.ok_; return answer; }
so tries access both base1
and derived
, it's friend of derived
, not of base1
. last sentence important thing, , changing friend function two template parameters solves issue.
Comments
Post a Comment