[英]Friends and template classes
How can i compile the below code without changing the status of int data? 如何在不更改int数据状态的情况下编译以下代码?
template<typename U>
void Test(U);
template< class T >
class B {
int data;
public:
friend void Test<>( T );
};
template<typename U>
void Test(U u) {
B < int> b1;
b1.data = 7;
}
int main(int argc, char *argv[])
{
char i;
Test(i);
system("PAUSE");
return 0;
}
The above code causes a compiler error, because b1.data
is private in Test
with U = char
. 上面的代码导致编译器错误,因为
b1.data
在Test
为U = char
私有。
The problem is that you are befriending Test<U>
to B<U>
(for the same U), but you are trying to access the internals of a B<int>
from a Test<char>
(different U). 问题是您正在将
Test<U>
与B<U>
结为好友(对于同一U),但是您试图从Test<char>
(不同的U)访问B<int>
的内部。
It would probably be simplest to make any Test friend of any B. 结识任何B的测试朋友可能是最简单的。
This compiled using VS2008. 这个是用VS2008编译的。 Not sure if it conforms to the standard.
不知道它是否符合标准。
#include <cstdlib>
template<typename U> void Test(U);
template< class T > class B {
int data;
public:
template <typename U > friend void Test(U);
};
template<typename U>
void Test(U u){
B < int> b1;
b1.data = 7;
}
int main(int argc, char *argv[])
{
char i;
Test(i);
system("PAUSE");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.