【问题标题】:Templated method pointer - can't match pointer for function argument模板化方法指针 - 无法匹配函数参数的指针
【发布时间】:2017-02-06 03:53:09
【问题描述】:

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

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 吗?我也试过&amp;TestClass::TestMethod,也不匹配。

【问题讨论】:

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


    【解决方案1】:

    您在调用_getWrapper 时明确指定了模板参数,而第一个参数指定为int 用于模板参数OBJECT,这是错误的。因为成员指针不能引用非类类型。

    改变

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

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

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

    _getWrapper(&testObj, &TestClass::TestMethod)
    

    顺便说一句:要从会员那里获取地址,您应该始终使用&amp;
    顺便说一句:我想TestClass::TestMethodpublic

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多