2

以下のような単純なクラスがあります。

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。

4

3 に答える 3

3
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たいのはどのインスタンスですか? それが呼び出し元の objectである場合は、別のパラメーターを提供する必要があるか、Alex が言うように使用して、次のように定義します。myfunctionfuncamyfunctionabind

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
    }
};
于 2013-01-18T11:26:42.220 に答える
2

使用し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); }
于 2013-01-18T11:20:30.817 に答える
1

あなたの質問をよく理解できたかどうかわかりませんが、std::functionandを使ってみてくださいstd::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)

于 2013-01-18T11:30:17.847 に答える