2

パラメータとして指示を出したいのですが:

execute_at_frame(int frame_number, <instruction>)
{
    for(f = 1 ; f < F_MAX ; f++)
    {
        /* other instructions */
        if (f == frame_number)
            /* execute <instruction> */
        /* other instructions */
    }
}
  • 呼び出しの1つのタイプ:execute_at_frame(5,execute(42));
  • 別の種類の呼び出し:execute_at_frame(6,process());

それ(または同様のもの)は可能ですか?

前もって感謝します :-)

4

5 に答える 5

3

std::bindはい、 (C ++ 11)を使用する場合:

template <class F>
void execute_at_frame(int frame_number, F instruction)
{
    for(int f = 1 ; f < F_MAX ; f++)
    {
        /* other instructions */
        if (f == frame_number)
            instruction();
        /* other instructions */
    }
}

/* ... */

execute_at_frame(5,process); // no bind for functions without parameters
execute_at_frame(5,std::bind(execute,42));

それ以外の場合は、指示用のインターフェースを準備する必要があります。

于 2012-12-06T12:55:30.087 に答える
2

パラメータ<instruction>は、関数ポインタ(つまり、関数へのポインタ)のいずれかexecuteです。executeまたは、メソッドを持つクラスのインスタンスへの参照にすることもできます。

于 2012-12-06T12:54:24.080 に答える
1

(必要に応じて)いくつかのパラメーターとともに関数ポインターを渡すことができます。次のようになります。

typedef void (*Instruction)(int);

void foo(int)
{
    // do something
}

void execute_at_frame(int frame_number, Instruction ins, int param)
{
    for(int f = 1 ; f < F_MAX ; f++)
    {
        /* other instructions */
        if (f == frame_number)
            ins(param);
    }
}

使用例:

execute_at_frame(1000, foo, 42);

可変個引数テンプレートを使用する場合は、任意の署名で機能させることができます。簡略化した例:

void foo(int)
{
}

float bar(int, char, double)
{
    return 1.0;
}

template<typename F, typename... Args>
void execute(F ins, Args... params)
{
    ins(params...);
}

int main()
{
    execute(foo, 1);
    execute(bar, 1, 'a', 42.0);
}

そのためにはC++11コンパイラが必要です。

于 2012-12-06T12:57:18.933 に答える
0

パラメータは、基本クラスポインタ、仮想関数を持つ派生クラスを指すこともできます

于 2012-12-06T13:01:55.507 に答える
0

関数をパラメーターとして使用するためのコード:

#include <functional>
#include <iostream>
using namespace std;

int instruction(int instruc)
{
     return instruc ;
}


template<typename F>
void execute_at_frame(int frame, const F& function_instruction)
{
     std::cout << function_instruction(frame) << '\n';
}


int main()
{
     execute_at_frame(20, instruction);  //  use reference
     execute_at_frame(40, &instruction); //  use pointer




  cout<<" \nPress any key to continue\n";
  cin.ignore();
  cin.get();

   return 0;
}
于 2012-12-06T13:43:43.127 に答える