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>?
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)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With