views:

57

answers:

3

I am trying to write an operator which converts between the differnt types of the same implementation. This is the sample code:

template <class T = int>
class A
{
public:
    A() : m_a(0){}

    template <class U>
    operator A<U>()
    {
        A<U> u;
        u.m_a = m_a; 
        return u;
    }
private:
    int m_a;
};

 int main(void)
{
    A<int> a;
    A<double> b = a;
    return 0;
}

However, it gives the following error for line u.m_a = m_a;.

Error 2 error C2248: 'A::m_a' : cannot access private member declared in class 'A' d:\VC++\Vs8Console\Vs8Console\Vs8Console.cpp 30 Vs8Console

I understand the error is because A<U> is a totally different type from A<T>. Is there any simple way of solving this (may be using a friend?) other than providing setter and getter methods? I am using Visual studio 2008 if it matters.

+2  A: 

VC10 accepts this:

template <class T = int>
class A
{
public:
    template< typename U>
    friend class A;

    A() : m_a(0){}

    template <class U>
    operator A<U>()
    {
        A<U> u;
        u.m_a = m_a; 
        return u;
    }
private:
    int m_a;
};
sbi
works fine..I didn't know I can declare a friend with a template parameter.
Naveen
+2  A: 

You can declare the conversion function as friend

template <class T = int>
class A
{
public:
    A() : m_a(0){}

    template <class U>
    operator A<U>()
    {
        A<U> u;
        u.m_a = m_a; 
        return u;
    }

    template <class U> template<class V>
    friend A<U>::operator A<V>();
private:
    int m_a;
};
Johannes Schaub - litb
A: 

You could construct the A<U> with the int directly.

DeadMG