Cannot access private member declared in class error when creating template

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 I get is int name<double>::h_ is private . How to fix the error?

+6
c ++ templates
source share
6 answers

name<int> and name<double> are different instances, and therefore, in fact, are different classes. Their private members cannot be used by default. You must make name<T> friend for everyone else name .

 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; } 
+7
source share

name<int> trying to access the private member name<double> . You should fix this by making the conversion function a friend, but the compilers I tried go havoc if you tried .

You can also make any name<T> friend name<U> to fix this.

 template <typename T> class name { public: name() : h_(0){} template <typename U> operator name<U>() { name<U> u; u.h_ = h_; return u; } template<typename U> friend class name; // <---- private: int h_; }; 
+3
source share

name<T> and name<U> considered by the compiler as two different classes, and it does not allow you to access private members of another class. How to fix it? Either redesign or give friendship. Or provide an accessory ... There are many ways to do this, the most suitable of them depends on your intentions. If I assume that your intention is correct, giving friendship may be a good idea, but I do not see the whole picture from your code.

+2
source share

You will need to add setters / getters (or friendship, or something else). The problem is that name<T> and name<U> are completely unrelated classes.

Alternatively, why don't you add another constructor for name(const T &h) : h_(h) {} ?

+1
source share

name<T> may differ from name<U> [for example: in your case]. Therefore, it is impossible to access the private members of another (if T and U are different types).

Add the following to the class definition.

 template<typename U> friend class name; 
0
source share

Name<T> potentially different from the type Name<U> , so encapsulation rules apply. Use accessors or friends.

0
source share

All Articles