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

时间:2017-02-06 03:53:09

标签: c++ templates variadic-templates member-function-pointers

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

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,也没有匹配。

1 个答案:

答案 0 :(得分:3)

您在调用var numbers = [1,2,1,0,3] numbers.sort { if $0.1 < $0.0 { print ($0.1) } return false } 时明确指定模板参数,并且第一个参数指定为模板参数_getWrapper的{​​{1}},这是错误的。因为成员指针不能引用非类类型。

更改

int

OBJECT

请注意,您可以依赖template type deduction,例如

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

顺便说一句:要从会员处获取地址,您应该始终使用_getWrapper<TestClass, int, float, bool>(&testObj, &TestClass::TestMethod) // ~~~~~~~~~~ 顺便说一句:我认为_getWrapper(&testObj, &TestClass::TestMethod) &

相关问题