[英]Template Friend Function / Class forward declaration
Why do we need template forward declaration for BlobPtr
and operator overloading for template.为什么我们需要BlobPtr
的模板前向声明和模板的运算符重载。
template <typename> class BlobPtr;
template <typename> class Blob;
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob {
friend class BlobPtr<T>;
friend bool operator==<T>
(const Blob<T>&, const Blob<T>&);
};
class BlobPtr<T>{};
Blob<char> ca;
Blob<int> ia;
For for nontemplate class, forward declaration is not needed.对于非模板 class,不需要前向声明。
class Blob {
type
class BlobPtr;
friend bool operator==
(const Blob&, const Blob&);
};
class BlobPtr{};
If you want to declare the template in a friend declaration, you can just do that, you don't need forward declarations:如果你想在朋友声明中声明模板,你可以这样做,你不需要前向声明:
template <typename T>
class Blob {
template <typename U>
friend class BlobPtr;
template <typename U>
friend bool operator==(const Blob<U>&, const Blob<U>&);
};
This declares all instances of the templates as friends, not just the matching one.这将模板的所有实例声明为朋友,而不仅仅是匹配的。 That is, BlobPtr<int>
and BlobPtr<long>
(and generally BlobPtr<Anything>
) are all friends of Blob<int>
.也就是说, BlobPtr<int>
和BlobPtr<long>
(通常是BlobPtr<Anything>
)都是Blob<int>
的朋友。
If you want to declare a particular specialization of a template as a friend (so that BlobPtr<int>
is a friend of Blob<int>
but BlobPtr<long>
is not), then you first need to tell the compiler that BlobPtr
is a template in the first place - that's what you need forward declaration for.如果您想将模板的特定特化声明为友元(因此BlobPtr<int>
是Blob<int>
的友元,但BlobPtr<long>
不是),那么您首先需要告诉编译器BlobPtr
是首先是模板 - 这就是您需要前向声明的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.