[英]C++: friend template class / template non-type parameter
I want to implement generic graph classes and I am still having problems which narrowed down to the following code: 我想实现通用图类,但仍然遇到问题,这些问题可以归结为以下代码:
template <class T> class B
{
template <T> friend class A;
};
template <class T> class A
{
private:
std::vector<B<T> *> myBs;
};
class C { };
This compiles pretty well unless I do something like this: 除非我做这样的事情,否则编译效果很好:
B<C> myB;
... which causes the following errors: ...这会导致以下错误:
B.h: In instantiation of ‘class B<C>’:
In file included from A.h:12:0,
from main.cpp:16:
main.cpp:30:10: required from here
B.h:15:1: error: ‘class C’ is not a valid type for a template non-type parameter
{
^
B.h:11:11: error: template parameter ‘class T’
template <class T> class A;
^
B.h:16:31: error: redeclared here as ‘<declaration error>’
template <T> friend class A;
Is my thinking absolutely wrong, am I missing something or is such a construct not possible, messy, odd or a very (...) very awful thing to do? 我的想法是绝对错误的,我是否缺少某些东西,或者这种构造不可能,凌乱,奇怪或非常(...)非常糟糕?
The problem is your friend
declaration. 问题是您的
friend
声明。 I suggest you declare the A
class first, and then use a simpler friend
declaration. 我建议您先声明
A
类,然后再使用更简单的friend
声明。 Like 喜欢
template<class T> class A;
template<class T>
class B
{
friend A<T>;
...
};
The question is whether you want to make just A<T>
a friend of B<T>
. 问题是您是否只想让
A<T>
成为B<T>
的朋友。 Then use Joachim's solution! 然后使用Joachim的解决方案!
If you want to make any A a friend, then you need to do this: 如果您想与任何A成为朋友,则需要执行以下操作:
template <class T> class B
{
template<class> friend class A;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.