I have a template base class, and a derived template class. The derived one has a an overloaded method with an argument that holds a reference to an object of the same type of the base class. If these weren't a template class, I would have made the derived class a friend of the base class so that I can access the base's protected members in this case, but how do I do this with templates?
template <typename T>
class base
{
// If this wasn't a template class, I would have done this:
// friend class derived;
public:
base(T val)
: val_(val)
{
}
virtual void assign(const base<T>& other)
{
val_ = other.val_;
}
protected:
T val_;
};
template <typename T>
class derived : public base<T>
{
public:
derived(T val)
: base<T>(val)
{
}
virtual void assign(const base<T>& other)
{
this->val_ = other.val_; // error: ‘int base<int>::val_’ is protected
}
};
int main()
{
derived<int> a(5);
derived<int> b(6);
b.assign(a);
return 0;
}