在以下C ++代码中(来自Microsoft COM头文件),以template<class Q>...
开头的部分是什么?
我也因其他原因而感到困惑,因为虽然使用了struct
,但它有类似于类的元素;例如,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); }
};
}
答案 0 :(得分:1)
以template<class Q> HRESULT WINAPI QueryInterface
开头的部分是模板成员函数。换句话说,它是一个函数模板,它是类(或结构,在本例中)的成员。
作为模板意味着您可以传递任何接口类型作为其参数,并且编译器将生成一个函数来查询对象以寻找该类型的接口:
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
的类型,因此当您传递IFoo **
时,Q
具有类型IFoo
,当您传递IBar **
时,Q
的类型为IBar
。
在C ++中,class
和struct
之间的唯一区别是class
中的成员可见性默认为private
,但struct
默认值到public
(因此public:
代码在这种情况下不会完成任何事情。)