My code is as follows
template <typename T>
class name
{
public:
name() : h_(0){}
template <typename U>
operator name<U>()
{
name<U> u;
u.h_ = h_;
return u;
}
private:
int h_;
};
int main(void)
{
name<int> a;
name<double> b = a;
return 0;
}
The error that I get is int name<double>::h_ is private
. How to fix the error?
name<int>
and name<double>
are different instantiations, and thus are actually different classes. Their private members cannot be shared by default. You need to make name<T>
friend to all other name
's.
template <typename T>
class name
{
public:
name() : h_(0){}
template <typename U>
operator name<U>()
{
name<U> u;
u.h_ = h_;
return u;
}
private:
int h_;
template <typename> // <--
friend class name; // <--
};
int main(void)
{
name<int> a;
name<double> b = a;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With