C++ Class member access problem with templates

后端 未结 2 1062
萌比男神i
萌比男神i 2020-12-20 13:37

Ive got a problem that if I have a template class, which in turn has a template method that takes a parameter of another instance of the class (with different template argum

2条回答
  •  忘掉有多难
    2020-12-20 13:50

    They are different types: templates construct new types from a template.

    You have to make other instantiations of your class friends:

    template class MyClass
    {
        T v;
    public:
        MyClass(T v):v(v){}
    
        templatevoid foo(MyClass obj)
        {
            std::cout << v     << " ";
            std::cout << obj.v << " ";
            std::cout << v + obj.v << std::endl;
        }
    
        // Any other type of MyClass is a friend.
        template 
        friend class MyClass;
    
        // You can also specialize the above:
        friend class MyClass; // only if this is a MyClass will the
                                   // other class let us access its privates
                                   // (that is, when you try to access v in another
                                   // object, only if you are a MyClass will
                                   // this friend apply)
    };
    

提交回复
热议问题