C++ Class member access problem with templates

后端 未结 2 1058
萌比男神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 <typename T>class MyClass
    {
        T v;
    public:
        MyClass(T v):v(v){}
    
        template<typename T2>void foo(MyClass<T2> obj)
        {
            std::cout << v     << " ";
            std::cout << obj.v << " ";
            std::cout << v + obj.v << std::endl;
        }
    
        // Any other type of MyClass is a friend.
        template <typename U>
        friend class MyClass;
    
        // You can also specialize the above:
        friend class MyClass<int>; // only if this is a MyClass<int> 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<int> will
                                   // this friend apply)
    };
    
    0 讨论(0)
  • 2020-12-20 14:16

    Add MyClass as friend class:

    template<typename T> class MyClass
    {
        template<typename TX>
        friend class MyClass;
     ...
    

    According to C++ Standard 14.5.3/3:

    A friend template may be declared within a class or class template. A friend function template may be defined within a class or class template, but a friend class template may not be defined in a class or class template. In these cases, all specializations of the friend class or friend function template are friends of the class or class template granting friendship. [Example:

    class A {
      template<class T> friend class B;  // OK
      template<class T> friend void f(T){ /* ... */ }  // OK
    };
    

    —end example]

    NOTE: You should know that the code above still could lead to an error with some compilers due to Core Issue #602 which is still open. Despite this, the code above compiles on GCC, Visual C++ and Comeau.

    To make only function foo a friend you could write the following:

    template<typename T> class MyClass
    {
        template<typename TY> template<typename TX> 
        friend void MyClass<TY>::foo(MyClass<TX>);
     ...
    
    0 讨论(0)
提交回复
热议问题