マップを使用して、演算子と関連するファンクターを格納できます。C++11 では、いくつかの微妙なエラーがあるかもしれませんが、これらの行に沿った何かが機能するはずです。C++03 では、関数ポインターへの変更や、マップ値の格納に使用するなど、いくつかの点を変更std::function
する必要があります。boost::function
std::make_pair
#include <functional> //for std::function and std::less et al.
#include <map> //for std::map
#include <stdexcept> //for std::invalid_argument
#include <string> //for std::string
struct StringComparer {
static bool compare( //split up to fit width
const std::string &oper,
const std::string &str0, const std::string &str1
) {
MapType::const_iterator iter = operations.find(oper);
if (iter == std::end(operations)) //check if operator is found
throw std::invalid_argument("No match for provided operator.");
return iter->second(str0, str1); //call the appropriate functor
}
private:
using MapType = std::map< //makes life easier, same as typedef
std::string,
std::function<bool(const std::string &, const std::string &)>
>;
static const MapType operations; //a map of operators to functors
};
const StringComparer::MapType StringComparer::operations = { //define the map
{"<", std::less<std::string>()}, //std::less is a functor version of <
{"<=", std::less_equal<std::string>()},
{">", std::greater<std::string>()},
{">=", std::greater_equal<std::string>()}
};
実際の動作も確認できます。このようなアプローチの良いところは、演算子をマップに追加するだけなので、演算子を簡単に追加できることです。