从函数指针中键入演绎作为模板参数

时间:2013-11-12 18:12:37

标签: c++ function-pointers class-template type-deduction

我是模板新手,使用它们时遇到一些问题。 我发布下面的代码,我无法编码。 如何做这件事需要帮助

我需要像函数指针作为模板参数传递给tester类,并将TClass实例作为参数传递给构造函数。在构造函数中,函数指针将用于将testFunc绑定到作为函数指针的tester类的成员变量。然后,当测试器类被销毁时,将调用testFunc。 无法解析模板的类型扣除

#include <iostream>

using namespace std;

template< class TClass, TClass::*fptr>
class tester
{

    public:
        tester(TClass & testObj, ...) //... refer to the arguments of the test function which is binded
        {
            //bind the function to member fptr variable
        }

        ~tester()
        {
            //call the function which was binded here
        }

    private:
        (TClass::*fp)(...) fp_t;
};

class Specimen
{
    public:
        int testFunc(int a, float b)
        {
            //do something
            return 0;
        }
}

int main()
{
    typedef int (Specimen::*fptr)(int,float);
    Specimen sObj;

    {
        tester<fptr> myTestObj(sObj, 10 , 1.1);
    }
    return 0
}

2 个答案:

答案 0 :(得分:0)

使用C ++ 11 std::bind

#include <functional>
#include <iostream>

class Specimen
{
public:
  int testFunc(int a, float b)
  {
    std::cout << "a=" << a << " b=" << b <<std::endl;
    return 0;
  }
};

int main()
{
  Specimen sObj;
  auto test = std::bind(&Specimen::testFunc, &sObj, 10, 1.1);
  test();
}

检查documentation

答案 1 :(得分:0)

我混合了std::functionstd::bind以接近您的问题:

template<typename F>
class tester
{
    function<F> func;
public:
    template <typename H, typename... Args>
    tester(H &&f, Args&&... args) : func(bind(f, args...))
    {
    }

    ~tester()
    {
        func();
    }
};

class Specimen
{
public:
    int testFunc(int a, float b)
    {
        return a + b;
    }
};

int main()
{
    Specimen sObj;

    tester<int()> myTestObj(&Specimen::testFunc, &sObj, 10 , 1.1);
}

Live code