【问题标题】:what is this c++ templated function doing这个 c++ 模板函数在做什么
【发布时间】:2013-04-27 01:25:06
【问题描述】:

我正在尝试围绕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)() 是什么?

任何帮助表示赞赏...

【问题讨论】:

  • R (T::*func)() 将变量定义为名为@9​​87654331@ 的函数指针,它是T 类的成员,不带任何参数(隐式this 除外)并返回R
  • 它真的编译了吗?据我所知,这将编译,仅当sizeof( void (T::*)() ) 大于100...等等,是C++ 还是这种脚本语言?...而且你没有T::* - 如果你仔细看是void (T::*)()

标签: c++ templates angelscript


【解决方案1】:

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
}

阅读更多here

【讨论】:

  • 太棒了,现在更有意义了 :) 谢谢@0x499602D2
猜你喜欢
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
相关资源
最近更新 更多