私はかなりの検索を行いましたが、 * () とクラススコープの組み合わせが構文の理解を大きく妨げており、編集ごとに新しいエラーがスローされています。
私がやろうとしていること:
MyClass.h にあるメンバー関数へのポインターの std::vector を宣言します。
MyClass.cpp のコンストラクターで、実際のメンバー関数を std::vector に割り当てます。
メンバー関数は静的ではありません
ありがとう!
私はかなりの検索を行いましたが、 * () とクラススコープの組み合わせが構文の理解を大きく妨げており、編集ごとに新しいエラーがスローされています。
私がやろうとしていること:
MyClass.h にあるメンバー関数へのポインターの std::vector を宣言します。
MyClass.cpp のコンストラクターで、実際のメンバー関数を std::vector に割り当てます。
メンバー関数は静的ではありません
ありがとう!
次のようなメンバー関数ポインターを使用できます (C++11 はその部分とは関係ありません)。
struct S {
int foo(){std::cout<<"foo"; return 0;}
int bar(){std::cout<<"bar"; return 0;}
};
int main() {
std::vector<int(S::*)()> funcs{&S::foo, &S::bar};
S s;
for (auto func : funcs) {
(s.*func)();
}
}
ただし、C++11 を使用する場合std::function
は、少しきれいにすることができます。
std::vector<std::function<int(S &)>> funcs{&S::foo, &S::bar};
S s;
for (auto func : funcs) {
func(s);
}
C++03 を使用する場合、Boost には がありboost::function
、これは似ています。
どこから使うのか気になります。C++ クラスのメンバー関数を呼び出すには、それを呼び出すためのインスタンス ポインターが必要です (各メンバー関数は、クラスの状態にアクセスするために this が必要です)。したがって、通常はメンバー関数ポインターをインスタンス ポインターと一緒に std::bind でラップし、結果を std::function に格納します。それらをベクトルに入れるには、すべて同じ署名が必要になります。
これはあなたが探していたものですか?
class P
{
typedef std::function<void (void)> func_t;
std::vector<func_t> functions;
public:
P()
{
functions.push_back(std::bind(&P::foo1, this));
functions.push_back(std::bind(&P::foo2, this));
functions.push_back(std::bind(&P::foo3, this));
}
void foo1(void)
{
std::cout << "foo1\n";
}
void foo2(void)
{
std::cout << "foo2\n";
}
void foo3(void)
{
std::cout << "foo3\n";
}
void call()
{
for(auto it = functions.begin(); it != functions.end(); ++it)
{
(*it)();
}
}
};
int main()
{
P p;
p.call();
}
OPからさらに明確にした後、私はこれを提案します:
class P
{
typedef std::function<void (void)> func_t;
std::map<const char*, func_t> functions;
public:
P()
{
functions["foo1"] = std::bind(&P::foo1, this);
functions["foo2"] = std::bind(&P::foo2, this);
functions["foo3"] = std::bind(&P::foo3, this);
}
void foo1(void)
{
std::cout << "foo1\n";
}
void foo2(void)
{
std::cout << "foo2\n";
}
void foo3(void)
{
std::cout << "foo3\n";
}
void call_by_name(const char* func_name)
{
functions[func_name]();
}
};
int main()
{
P p;
p.call_by_name("foo1");
p.call_by_name("foo2");
p.call_by_name("foo3");
}