这个c++模板化函数在做什么?

what is this c++ templated function doing

本文关键字:什么 函数 c++ 这个      更新时间:2023-10-16

我想写一个薄薄的包装围绕AngelScript。我在弄清楚如何环绕一个特定的结构体时遇到了麻烦。

下面是我要包装的结构体asSMethodPtr的结构体定义:

template <int N>
struct asSMethodPtr
{
    template<class M>
    static asSFuncPtr Convert(M Mthd)
    {
        // This version of the function should never be executed, nor compiled,
        // as it would mean that the size of the method pointer cannot be determined.
        int ERROR_UnsupportedMethodPtr[N-100];
        asSFuncPtr p;
        return p;
    }
};

以下是asSFuncPtr的定义:

struct asSFuncPtr
{
    union
    {
        char dummy[25]; // largest known class method pointer
        struct {asFUNCTION_t func; char dummy[25-sizeof(asFUNCTION_t)];} f;
    } ptr;
    asBYTE flag; // 1 = generic, 2 = global func
};

这是我找到的代码(取自AngelBinder库),允许我"包装"它:

template<typename R> ClassExporter& method(std::string name, R (T::*func)())
{
    MethodClass mthd(name, Type<R>::toString(), asSMethodPtr< sizeof( void (T::*)() ) >::Convert( AS_METHOD_AMBIGUITY_CAST( R (T::*)()) (func) ));
    this->_methods.push(mthd);
    return *this;
}

不幸的是,我不知道这段代码在做什么…

T::*应该做什么?指向类类型的指针?

R (T::*func)()是什么?

T::*是指向成员的指针。R (T::*func)()是指向成员函数的指针,该成员函数返回R并接受0个形参。例如:

struct S
{
    int f()
    {
        return 5;
    }
    int x = 10;
};
int main()
{
    S s;
    int S::* ptr = &S::x;
    std::cout << s.*ptr; // 10
    int (S::*f_ptr)() = &S::f;
    std::cout << (s.*f_ptr)(); // 5
}