问题描述
我有一个简单的类X,和一组模板化类Y< T,U>.我希望所有第一个模板化参数恰好是X的类Y都成为X本身的朋友.以下希望传达出我想要的内容,但是友友语句给出了编译错误.
I have a simple class X, and set of templatized classes 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. 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?
谢谢,马特
推荐答案
对于您问题的非部分内容,语法为:
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.
使用C ++ 11,您实际上可以为模板别名添加朋友:
With C++11 you can actually friend a templated alias:
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).
这篇关于朋友课程的部分模板专业化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!