0

在以下 C++ 代码(来自 Microsoft COM 头文件)中,以 开头的部分是什么template<class Q>...

由于其他原因,我也完全感到困惑,因为虽然 astruct正在使用中,但它具有类元素;例如,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); }
    };
  }
4

1 回答 1

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从您传递的参数的类型推断出类型,因此当您传递 an 时IFoo **Q具有 type IFoo,当您传递 an 时IBar **Q具有 type IBar

class在 C++ 中, a和之间的唯一区别struct是成员可见性在 aclass默认为private,但在 astruct默认为public(因此public:在这种情况下标记没有完成任何事情)。

于 2015-05-05T13:57:20.513 回答