我有一个问题,如果我有一个模板类,它又有一个模板方法,它接受该类的另一个实例的参数(具有不同的模板参数),它不能访问被传递的类的受保护或私有成员一个参数,例如:
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); }
有没有可以说MyClass< T>中的方法有完全访问MyClass< SomeOtherT>?
解决方法
它们是不同的类型:模板从模板构建新类型.
你必须对你的班级朋友做其他的例子:
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) };