[英]partial template specialization for friend classes?
I have a simple class X, and set of templatized classes Y<T,U>.我有一个简单的 X 类和一组模板化类 Y<T,U>。 I'd like all classes Y where the first templatization parameter happens to be X to be a friend of X itself.我希望第一个模板化参数恰好是 X 的所有类 Y 成为 X 本身的朋友。 The following hopefully conveys what I want, but the friend statement gives a compile error.以下希望传达了我想要的内容,但朋友声明给出了编译错误。
template<typename T, typename U>
class Y {
};
class X {
public:
X(int value) : i(value) {}
const int& getI() const { return i; }
private:
int i;
template<class U> friend class Y<X,U>;
};
I'm not sure templatization of friend statements is allowed at all (let alone partial templatization of friend statements).我不确定是否允许对朋友语句进行模板化(更不用说对朋友语句进行部分模板化了)。 Is there a way to do this?有没有办法做到这一点? Or am I stuck listing out all the friends one-by-one?还是我被卡在一张一张地列出所有朋友?
Thanks, Matt谢谢,马特
The friend declaration page on cppreference.com specifies: cppreference.com 上的朋友声明页面指定:
Friend declarations cannot refer to partial specializations, but can refer to full specializations友元声明不能引用部分特化,但可以引用完全特化
So as chtz said you can have a non-partial specialization friend.因此,正如 chtz 所说,您可以拥有一个非部分专业化的朋友。
Edit:编辑:
See also another answer on stackoverflow: https://stackoverflow.com/a/11046918/5776353另请参阅有关 stackoverflow 的另一个答案: https ://stackoverflow.com/a/11046918/5776353
For the non-partial part of your question, the syntax is:对于您问题的非部分部分,语法为:
class X {
template<class T, class U> friend class Y;
};
I guess, in most cases that should be sufficient.我想,在大多数情况下,这应该足够了。
With C++11 you can actually friend a templated alias:使用 C++11,您实际上可以使用模板化别名:
template<typename T, typename U>
class Y { };
class X {
public:
X(int value) : i(value) {}
const int& getI() const { return i; }
private:
int i;
template<class U> using YX = Y<X,U>;
template<class U> friend class YX;
};
However, that does not seem to work (I'm not sure if the friend declaration above has any effect at all).但是,这似乎不起作用(我不确定上面的朋友声明是否有任何效果)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.