c++ - 模板函数将参数函数指针指向类方法

标签 c++ templates pointer-to-member

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

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 -

想法/代码/原因?

问候, 法鲁克阿尔沙德。

最佳答案

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。您希望 myfunction 调用 func 的哪个 A 实例?如果它是调用者的对象 a,那么 myfunction 需要另一个参数来提供 a,或者使用 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
    }
};

关于c++ - 模板函数将参数函数指针指向类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14397733/

相关文章:

c++ - 库设计困惑.. "public"/"private"(template) headers, library files..?

c++ - 打印对象的文本表示

c++ - 将成员函数指针传递给父类

c++ - 最简单的代码上的“imspossible”错误

c++ - 安全的 enable_shared_from_this 用法

c++ - g++ 和 clang++ 不同的行为与指向可变参数模板函数的指针

C++:通过基类中定义的函数指针从派生调用函数

c++ - 指向 shared_ptr 成员变量的指针

c++ - Dll 与静态库(MSVC9 运行时库选项)

c++ - 我如何以不同方式实现此冒泡排序?