【问题标题】:Conversion between different template instantiation of the same template同一模板的不同模板实例化之间的转换
【发布时间】:2010-06-04 12:15:50
【问题描述】:

我正在尝试编写一个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&lt;U&gt;A&lt;T&gt; 是完全不同的类型。除了提供 setter 和 getter 方法之外,是否有任何简单的方法来解决这个问题(可能是使用朋友?)?如果重要的话,我正在使用 Visual Studio 2008。

【问题讨论】:

  • 不能把值传给构造函数吗?
  • @sbi: 也许我可以..但是我想知道如何解决这个问题,如果我不能将值作为构造函数参数传递。

标签: c++ templates type-conversion


【解决方案1】:

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

【讨论】:

  • 工作正常..我不知道我可以用模板参数声明一个朋友。
【解决方案2】:

您可以将转换函数声明为朋友

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

【讨论】:

    【解决方案3】:

    你可以直接用 int 构造A&lt;U&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多