2014-10-01 6 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

ответ

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

DEMO

+1

Templating заявление друга? Вы просто взорвали мой разум ... – iwolf

+1

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

+0

Прекрасно, спасибо! –

Смежные вопросы