member templates - access problem

Hello Everyone,

I am getting compiler "error C2248: 'CTest<T>::m_element' : cannot access private member declared in class 'CTest<T>' ." I don't know why the private member variable can't be accessed in this case? Please explain the problem.


template <typename T>
class CTest
{
.....
void Add(T& tempElement);

template <typename T2>
CTest<T>& operator = (CTest<T2>& rhs);

private:

T m_element;

};

template <typename T>
template <typename T2>
CTest<T>& CTest<T>::operator =(CTest<T2>& rhs)
{
m_element = rhs.m_element; // Error C2248:

// m_element = 10 -> I can access the private member using this statement.

return *this;
}


void main()
{

CTest<int> obj_1;
CTest<float> obj_2;

float val_1 = 23.89;
int val_2 = 50;

obj_2.Add(val_1);
obj_1.Add(val_2);

obj_1 = obj_2;

}

[code] "Please use code tags" [/code]
CTest<T> and CTest<T2> are different types.
If you don't want to provide public accessors, then make them friend
1
2
3
template<class T>
class CTest{
  template <class T2> friend class CTest;



Also, main must return int
Last edited on
The simple solution would be to provide a public accessor function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template < typename T > class CTest
{
    public:
        CTest() : m_element( T() ) {}
        template < typename U > explicit CTest( const U& v ) : m_element(v) {}

        // ...

        const T& element() const { return m_element ; }

        template < typename U > CTest<T>& operator= ( const CTest<U>& that )
        { m_element = that.element() ; return *this ; }

        // ...

    private: T m_element ;
};


A more intricate solution would be to use a friend declaration.
See: http://www.devx.com/cplus/10MinuteSolution/30302/1954
@JLBorges

Thanks, but I want to understand the sample using different types.

@ne555

Thanks. It works well by adding friend function and very much convincing too.

1
2
3
4
5
6
7
8
9
10
template <typename T>
template <typename T2>
CTest<T>& CTest<T>::operator =(CTest<T2>& rhs)
{

// here private member variables can be accessible for the calling object & not an issue.  
// But the passed object is a different type, CTest <T2>. 
// Thats why we couldn't able to access rhs's private member variable, right ?

}



Topic archived. No new replies allowed.