问题描述
是否有可能使部分模板规范成为朋友类? IE.认为您具有以下模板类
is it possible to somehow make a partial template specification a friend class? I.e. consider you have the following template class
template <class T> class X{
T t;
};
现在您有部分专长,例如,指针
Now you have partial specializations, for example, for pointers
template <class T> class X<T*>{
T* t;
};
我想完成的是,每个可能的X<T*>
是X<S>
的任何S
的朋友类. IE. X<A*>
应该是X<B>
的朋友.
What I want to accomplish is that every possible X<T*>
is a friend class of X<S>
for ANY S
. I.e. X<A*>
should be a friend of X<B>
.
当然,我想到了X中常用的模板朋友声明:
Of course, I thought about a usual template friend declaration in X:
template <class T> class X{
template <class S> friend class X<S*>;
}
但是,这无法编译,g ++告诉我:
However, this does not compile, g++ tells me this:
test4.cpp:34:15:错误:"template<class T> class X
"的专业化必须出现在名称空间范围内
test4.cpp:34:15: error: specialization of 'template<class T> class X
' must appear at namespace scope
test4.cpp:34:21:错误:部分专业化'X<S*>
'被声明为'朋友'
test4.cpp:34:21: error: partial specialization 'X<S*>
' declared 'friend'
这根本不可能还是有解决方法?
Is this not possible at all or is there some workaround?
我问的原因是,我需要一个X<T*>
中的构造函数,该构造函数可以从任意X<S>
(S
必须是T
的子类型)创建此类.
The reason why I am asking is that I need a constructor in X<T*>
that creates this class from an arbitrary X<S>
(S
must be a subtype of T
).
代码如下:
template <class T> class X<T*>{
T* t;
template<class S>
X(X<S> x) : t(&(x.t)) {} //Error, x.t is private
}
现在,编译器当然会抱怨x.t
在构造函数中不可见,因为它是私有的.这就是为什么我需要部分专业化朋友课程的原因.
Now, the compiler complains, of course, that x.t
is not visibile in the constructor since it is private. This is why I need a partial specialization friend class.
推荐答案
在C ++中,您可以在四个级别上授予private
以外的权限.
In C++, you can grant access beyond private
on four levels.
- 完全
public
访问(请参阅pmr的答案) - 继承层次结构内的访问权限(
protected
,此处无关) - 到基本模板
friend
(请参阅此答案) - 非模板或完全专用的
friend
(太弱而无法解决您的用例)
- completely
public
access (see pmr's answer) - access within inheritance hierarchy (
protected
, irrelevant here) - to a base template
friend
(see this answer) - to a non-template or fully specialized
friend
(too weak to solve your use case)
后两种友谊之间没有中间途径.
摘自C ++标准的第14.5.4节:.
From §14.5.4 of the C++ standard:.
以下声明将使您能够实现所需的内容.它使您可以自由地访问模板的任何其他专业化内容,但仍然只能在X
中进行.它比您要求的要宽松一些.
The following declaration will allow you to implement what you need. It gives you a free hand to access any specialization of your template from any other specialization, but still only within X
. It is slightly more permissive than what you asked for.
template<class T> class X
{
template<class Any> friend class X;
public:
...
};
这篇关于C ++模板:部分模板规范和朋友类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!