【问题标题】:type deduction from a function pointer as template argument从函数指针作为模板参数的类型推导
【发布时间】:2013-11-12 18:12:36
【问题描述】:

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

我需要将函数指针作为模板参数传递给测试器类,并将 TClass 实例作为参数传递给构造函数。在构造函数中,函数指针将用于将 testFunc 绑定到测试器类的成员变量,该成员变量是函数指针。然后,当测试器类被销毁时,将调用 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
}

【问题讨论】:

  • 你可以使用 C++11 可变参数模板吗?您可以使用为您完成整个工作的 boost 或 std lib 函数吗?
  • 我认为您不能简单地使用TClass::*fptr 作为模板参数,因为缺少签名。
  • @GuilhermeBernal 在回答中使用std 给出示例。

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


【解决方案1】:

使用 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

【讨论】:

    【解决方案2】:

    我混合了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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 2021-06-22
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多