Can different instantiations of the same template can access others' private member?

P

PengYu.UT

For example, the following code has an error. I'm wondering what I
should do to make it correct, without declare m_t as public or use a
public member function to access it.

Ideally, example<T> and example<T1> should be declared as friend
classes. But I just don't know how to do that for any arbitrary T and
T1.



template <typename T>
class example{
public:
example(const T &t) : m_t(t){}
template <typename T1>
example(const example<T1> &ex1){
m_t = ex1.m_t; //error
}
private:
T m_t;
};

main(){
example<int> ex1(10);
example<double> ex2(ex1);
}


main.cc: In constructor `example<T>::example(const example<T1>&) [with
T1 =
int, T = double]':
main.cc:15: instantiated from here
main.cc:10: error: `int example<int>::m_t' is private
main.cc:7: error: within this context
 
V

Victor Bazarov

For example, the following code has an error. I'm wondering what I
should do to make it correct, without declare m_t as public or use a
public member function to access it.

Ideally, example<T> and example<T1> should be declared as friend
classes. But I just don't know how to do that for any arbitrary T and
T1.



template <typename T>
class example{

template<typename U> friend class example; // any instantiation
// of 'example' is a friend
// of all others (and this
// one as well)
public:
example(const T &t) : m_t(t){}
template <typename T1>
example(const example<T1> &ex1){
m_t = ex1.m_t; //error
}
private:
T m_t;
};

main(){

int main(){
example<int> ex1(10);
example<double> ex2(ex1);
}


main.cc: In constructor `example<T>::example(const example<T1>&) [with
T1 =
int, T = double]':
main.cc:15: instantiated from here
main.cc:10: error: `int example<int>::m_t' is private
main.cc:7: error: within this context

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top