简体   繁体   English

从函数指针作为模板参数进行类型推导

[英]type deduction from a function pointer as template argument

I am new to template and have a bit of problem using them. 我是模板的新手,使用它们时遇到了一些问题。 I am posting the code below which I am not able to code for. 我要发布下面无法编写代码的代码。 Need help in how to do this piece 在如何做这件事情上需要帮助

I need someething like a function pointer being passed as a template argument to the tester class and the TClass instance being passed as the parameter to the constructor. 我需要某种东西,例如将函数指针作为模板参数传递给测试器类,并将TClass实例作为参数传递给构造函数。 In the constructor the function pointer will be used to bind the testFunc to a member variable of the tester class which is a function pointer. 在构造函数中,函数指针将用于将testFunc绑定到tester类的成员变量,该成员变量是函数指针。 Then while the tester class is destroyed the testFunc will be called. 然后,当测试器类被破坏时,将调用testFunc。 No able to resolve the type deduction for the template 无法解决模板的类型推导

#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
}

using C++11 std::bind : 使用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();
}

Check the documentation . 检查文档

I mixed std::function and std::bind to get close to your problem: 我混合使用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 现场代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM