c++ - 访问模板类的 protected 属性

标签 c++ templates friend

以下代码不起作用,因为 t 成员函数无法访问其参数对象的属性。

如何将模板类A的模板方法t声明为A的友元函数?

对于没有template的代码,不需要声明friend。

代码:

template <typename T>
class A{
    protected:
        T a;
    public:
        A(int i){
            a = i;
        }
        template <typename T1>
        void t(const A<T1> & Bb){
            a = Bb.a;
        }
};
int main(void){
    A<int> Aa(5);
    A<float> Bb(0);
    Aa.t(Bb);
}

编译器错误(icc test.cpp):

test.cpp(11): error #308: member "A<T>::a [with T=float]" (declared at line 4) is inaccessible
              a = Bb.a;
                     ^
          detected during instantiation of "void A<T>::t(const A<T1> &) [with T=int, T1=float]" at line 17

没有模板的代码:

class A{
    protected:
        int a;
    public:
        A(int i){
            a = i;
        }
        void t(const A & Bb){
            a = Bb.a;
        }
};
int main(void){
    A Aa(5);
    A Bb(0);
    Aa.t(Bb);
}

最佳答案

您可以使所有模板实例成为彼此的 friend 。

template <typename T>
class A {
   protected:

      // This makes A<int> friend of A<float> and A<float> friend of
      // A<int>
      template <typename T1> friend class A;

      T a;
   public:
      A(int i){
         a = i;
      }
      template <typename T1>
         void t(const A<T1> & Bb){
            a = Bb.a;
         }
};
int main(void){
   A<int> Aa(5);
   A<float> Bb(0);
   Aa.t(Bb);
}

关于c++ - 访问模板类的 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536744/

相关文章:

c++ - 你如何为 clang 和 gcc 编写一个 makefile?

c++ - 访问父类变量

c++ - 如何破坏 C++ 接受函数?

c++ - 如何默认构造迭代器的value_type作为函数中的默认参数?

javascript - Backbone/Marionette JST 模板 - 没有错误,但未显示 View

c++ - 以下模板代码的奇怪行为

c++ - Friend 函数,期望 Primary Expression before 。 token

c++ - 如何使 C++ 类与 stringstream 对象兼容?

c++ - 如何查看类(class)友情?

c++ - friend 混入模板?