1

私は以下の関数を書いていましたが、おそらくもっと良い方法があるのではないかと考え始めました。ただし、Google はあまり成果を上げていないため、洞察をいただければ幸いです。私も整数を含む非常によく似た状況にあります。

bool compare_strs (std::string operator_, std::string str_0, std::string str_1)
{
    if (operator_ == ">")
    {
        return str_0 > str1;
    }
    else if (operator_ == "<")
    {
        return str_0 < str1;
    }
    else if (operator_ == "<=")
    {
        return str_0 <= str1;
    }
    else
    {
        return str_0 >= str1;
    }
}
4

2 に答える 2

3

マップを使用して、演算子と関連するファンクターを格納できます。C++11 では、いくつかの微妙なエラーがあるかもしれませんが、これらの行に沿った何かが機能するはずです。C++03 では、関数ポインターへの変更や、マップ値の格納に使用するなど、いくつかの点を変更std::functionする必要があります。boost::functionstd::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>()}
};

実際の動作も確認できます。このようなアプローチの良いところは、演算子をマップに追加するだけなので、演算子を簡単に追加できることです。

于 2012-10-12T19:51:01.093 に答える
0

他の人が述べたように、まずなぜこれを行っているのかを自問する必要があります - より良い解決策がある可能性があります。ただし、これを使用すると、次のようなことができます。

template <typename T1, typename T2>
bool mycompare(std::string operator_, const T1 & _lhs, const T2 & _rhs)
{
    if (operator_ == ">")
    {
        return _lhs > _rhs;
    }
    else if (operator_ == "<")
    {
        return _lhs < _rhs;
    } 
    //etc.
    else
    {
        throw new exception("Invalid operator");
    }
}
于 2012-10-12T19:50:16.910 に答える