これは、C++ では直接可能ではありません。C++ はコンパイル済み言語であるため、関数と変数の名前は実行可能ファイルには存在しません。したがって、コードが文字列を関数の名前に関連付ける方法はありません。
関数ポインターを使用して同様の効果を得ることができますが、この場合、メンバー関数も使用しようとしているため、問題が少し複雑になります。
少し例を挙げますが、コードを書くのに 10 分を費やす前に答えを得たかったのです。
編集:ここに私が何を意味するかを示すコードがあります:
#include <algorithm>
#include <string>
#include <iostream>
#include <functional>
class modify_field
{
public:
std::string modify(std::string str)
{
return str;
}
std::string reverse(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
};
typedef std::function<std::string(modify_field&, std::string)> funcptr;
funcptr fetch_function(std::string select)
{
if (select == "forward")
return &modify_field::modify;
if (select == "reverse")
return &modify_field::reverse;
return 0;
}
int main()
{
modify_field mf;
std::string example = "CAT";
funcptr fptr = fetch_function("forward");
std::cout << "Normal: " << fptr(mf, example) << std::endl;
fptr = fetch_function("reverse");
std::cout << "Reverse: " << fptr(mf, example) << std::endl;
}
もちろん、関数を に格納したい場合はmap<std::string, funcptr>
、それは完全に可能です。