[英]Conversion between different template instantiation of the same template
我正在嘗試編寫一個在同一實現的不同類型之間轉換的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;
行,它會產生以下錯誤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。
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;
};
您可以將轉換函數聲明為好友
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;
};
您可以直接使用int構造A<U>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.