模板化方法指针 - 无法匹配函数参数的指针

Templated method pointer - can't match pointer for function argument

本文关键字:指针 函数 参数 方法      更新时间:2023-10-16

我正在制作一个这样的方法指针包装器:

template<typename OBJECT, typename... ARGS>
method_wrapper<ARGS...> _getWrapper(OBJECT* object, void (OBJECT::*method)(ARGS...))
{
    //irrelevant
}

问题就在_getWrapper的召唤下:

class TestClass
{
    void TestMethod(int a, float b, bool c)
    {
        std::cout<<a<<std::endl;
        std::cout<<b<<std::endl;
        std::cout<<c<<std::endl;
    }
};
int main()
{
TestClass testObj;
method_wrapper<int, float, bool> wrap = _getWrapper<int, float, bool>(&testObj, TestClass::TestMethod);
wrap.callInternal(1000, 3.14, true);
//...
system("pause");
return 0;
}

无论我试图以何种方式传递_getWrapper中的论点,它仍然告诉我:

没有与参数列表匹配的重载函数实例

OBJECT::*method不是直接匹配TestClass::TestMethod吗?我也试过&TestClass::TestMethod,也不匹配。

您在调用_getWrapper时显式指定了模板参数,并且第一个参数被指定为模板参数OBJECTint,这是错误的。因为成员指针不能引用非类类型。

改变

_getWrapper<int, float, bool>(&testObj, TestClass::TestMethod)

_getWrapper<TestClass, int, float, bool>(&testObj, &TestClass::TestMethod)
//          ~~~~~~~~~~

请注意,您可以仅依靠模板类型推断,例如

_getWrapper(&testObj, &TestClass::TestMethod)

顺便说一句:为了从成员那里获取地址,您应该始终使用&
顺便说一句:我想TestClass::TestMethodpublic.