2014-10-01 18 views
3

請看下面的例子:如何在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>(); 
    } 
}; 

我想所有類型的「裁判」的對象才能夠訪問對方的保護構造。有什麼辦法可以做到這一點?

+2

你試過被'friend'ly? – Yakk 2014-10-01 17:29:43

回答

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

DEMO

+1

模板朋友聲明?你只是吹了我的腦海... – iwolf 2014-10-01 17:35:17

+1

http://stackoverflow.com/questions/8967521/c-class-template-with-template-class-friend-whats-really-going-on-here – iwolf 2014-10-01 17:39:10

+0

美麗,謝謝! – 2014-10-01 17:42:29