如何访问其他模板类实例的私有成员? [英] How to access private members of other template class instances?

查看:41
本文介绍了如何访问其他模板类实例的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个极小的例子将无法编译,因为A无法访问A中的私有成员i>

This extremely minimal example will fail to compile because A<int> cannot access the private member i in A<double>

template <class T>
class A {
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}

我找不到让这些模板实例成为朋友的正确方法.

I cannot find the correct way to make those template instances friends.

推荐答案

template <class T>
class A {
    template<class U>
    friend class A;
    int i;
  public:
    template <class U>
    void copy_i_from( const A<U> & a ){
        i = a.i;
    }
};

int main(void) {
    A<int> ai;
    A<double> ad;
    ai.copy_i_from(ad);
    return 0;
}

这篇关于如何访问其他模板类实例的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆