繁体   English   中英

模板函数,将参数函数指针指向类方法

[英]template function taking argument function pointer to a class method

我有一个简单的课程,如下所述。

typedef mytype int;
typedef mytype2 float;

class A {
     .
     .
     void run (mytype t) { .... do something with t ..... }
     .
     .
}

我有另一个我在其中创建了模板函数(使其独立于A类)的类,该模板函数应将指向它的函数指针(即A类方法运行)连同其参数一起使用。

class B {
     .
     template< // how it should be defined >
             void myfunction ( // how parameters will be passed ) { }

驱动程序应该像

      A a
      B b
      C c
      b.myfunction(&A::run, mytype);     // Or how it should be called
      b.myfunction(&B::run, mytype2);    // - do -

想法/代码/原因?

此致,Farrukh Arshad。

class B {
    template <typename T>
    void myfunction(void (T::*func)(mytype), mytype val) {
        (some_instance_of_T.*func)(val); // or whatever implementation you want
    }
};

参数func定义为T的非静态成员函数的指针,采用mytype并返回void

您需要从某个地方获取some_instance_of_T 什么情况下的A做你想做myfunction调用func吗? 如果是调用方的对象a ,则myfunction需要另一个参数来提供a ,或者使用Alex所说的bind并定义:

class B {
    template <typename Functor>
    void myfunction(Functor f, mytype val) {
        f(val); // or whatever implementation you want
    }
};

或者如果您想限制用户传入的内容的类型:

class B {
    void myfunction(std::function<void(mytype)> f, mytype val) {
        f(val); // or whatever implementation you want
    }
};

使用std::bind ;

using namespace std::placeholders;
b.myfunction(std::bind(&A::run, a, _1), mytype);

定义B如下

class B {
     .
     template<typename Callable, typename Arg>
             void myfunction (Callable fn, Arg a) {fn(a); }

我不确定我是否很好地理解了您的问题,但是您可能想尝试使用std::functionstd::bind ,例如:

#include <functional>
#include <iostream>

struct A
{
    void run(int n)
    {
        std::cout << "A::run(" << n << ")" << std::endl;
    }
};

struct B
{
    typedef std::function< void( int ) > function_type;

    void driver(function_type f, int value)
    {
        std::cout << "B::driver() is calling:" << std::endl;
        f( value );
    }
};


int main()
{
    A a;
    B b;
    b.driver( 
        std::bind<void>(&A::run, &a, std::placeholders::_1), 
        10
    );
}

输出:

B :: driver()正在呼叫:

A ::运行(10)

暂无
暂无

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

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