在下面的C ++代码(来自Microsoft COM头文件)中,以开头的部分是template<class Q>...
什么?
我也由于其他原因而感到完全困惑,尽管struct
使用了a,但是它具有类元素。例如public
关键字。
extern "C++" {
struct IUnknown {
public:
virtual HRESULT WINAPI QueryInterface(REFIID riid,void **ppvObject) = 0;
virtual ULONG WINAPI AddRef(void) = 0;
virtual ULONG WINAPI Release(void) = 0;
template<class Q> HRESULT WINAPI QueryInterface(Q **pp) { return QueryInterface(__uuidof(*pp),(void **)pp); }
};
}
开头的部分template<class Q> HRESULT WINAPI QueryInterface
是模板成员函数。换句话说,它是一个函数模板,是一个类(在这种情况下为struct)的成员。
成为模板意味着您可以传递任何接口类型作为其参数,并且编译器将生成一个函数来查询对象以获取该类型的接口:
IFoo *x;
IBar *y;
if (foo.QueryInterface(&x) != S_OK) {
// use x->whatever to invoke members of IFoo
}
if (foo.QueryInterface(&y) != S_OK) {
// use y->whatever to invoke members of IBar
}
由于它是一个函数模板,因此编译器会根据Q
您传递的参数的类型推导其类型,因此,当您传递an时IFoo **
,Q
具有类型IFoo
,而当您传递an时IBar **
,Q
具有type IBar
。
在C ++中,一个之间的唯一区别class
和struct
处于该构件的可视性class
默认private
,但在struct
默认public
(所以public:
标签没有实现在这种情况下任何东西)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句