Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class member access problem with templates

Tags:

c++

templates

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 arguments), that it can not access protected or private members of the class passed as a parameter, eg:

template<typename T>class MyClass
{
    T v;
public:
    MyClass(T v):v(v){}

    template<typename T2>void foo(MyClass<T2> obj)
    {
        std::cout << v     << " ";
        //error C2248: 'MyClass<T>::v' : cannot access private member declared in class 'MyClass<T>'
        std::cout << obj.v << " ";
        std::cout << v + obj.v << std::endl;
    }
};
int main()
{
    MyClass<int> x(5);
    MyClass<double> y(12.3);
    x.foo(y);
}

Is there someway to say that methods in MyClass<T> have full access to MyClass<SomeOtherT>?

like image 926
Fire Lancer Avatar asked Oct 21 '09 07:10

Fire Lancer


1 Answers

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)
};
like image 104
GManNickG Avatar answered Nov 12 '22 19:11

GManNickG