2010-06-04 57 views
2

我正在尝试编写一个operator,它在相同实现的不同类型之间进行转换。这是示例代码:同一模板的不同模板实例化之间的转换

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; 
} 

但是,它为行u.m_a = m_a;提供以下错误。

错误2错误C2248: 'A :: M_A': 不能访问私有成员声明 在 'A' d类:\ VC++ \ Vs8Console \ Vs8Console \ Vs8Console.cpp 30 Vs8Console

我知道错误是因为A<U>是与A<T>完全不同的类型。除了提供setter和getter方法之外,有没有解决这个问题的简单方法(可能是使用朋友?)?如果它很重要,我正在使用Visual Studio 2008。

+0

你不能将值传递给构造函数吗? – sbi 2010-06-04 12:31:19

+0

@sbi:可能是我可以......但想知道如何解决这个问题,如果我不能传递值作为构造参数。 – Naveen 2010-06-04 12:36:23

回答

3

VC10接受这一点:

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; 
}; 
+0

工作正常..我不知道我可以用模板参数声明一个朋友。 – Naveen 2010-06-04 12:40:35

3

可以声明转换功能的朋友

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; 
}; 
0

你可以构建A<U>直接与INT。