在为请求选择服务的情况下,使用Boost ICL而不是for_each是否可能且合理

Is it possible and resonable to use Boost ICL instead of for_each in case of selecting a service for request?

本文关键字:each for 是否 服务 选择 请求 情况下 ICL Boost 使用      更新时间:2023-10-16

我有一个request结构,其中有std::vector<std::string> arguments。我有std::map<std::string, std::vector<std::string> > services,其中key是服务名称,value是服务响应的参数向量。不同服务的参数可能重叠(N服务可能具有相同或部分相同的参数)。我需要找到与给定请求相对应的所有服务。我想知道使用Boost ICL而不是我用于服务选择的当前for_each是否会更好(从代码的易用性或阅读性以及请求选择速度来看,最重要的是)?

我会选择可读性最强的变体。如果性能有问题,只需将参数(集)的适用服务缓存到多映射中即可。

如果我的想法是正确的,下面显示了一些c++11/boost语法糖,它展示了我的可读性:

#include <boost/range/numeric.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
typedef std::vector<std::string> args_t;
typedef std::map<std::string, args_t> service_map;
struct applicable
{
    template <typename T>
        applicable(const T& args) : _args(args) { }
    bool operator()(const service_map::value_type& svc) const
    {
        for (auto& a:_args)
            if (svc.second.end() == boost::find(svc.second, a))
                return false;
        return true;
    }
  private: args_t _args;
};
int main(int argc, const char *argv[])
{
    using namespace boost::adaptors;
    static const service_map services { 
        { "A", { "1","2","3" } }, 
        { "B", { "2","3","4" } },
        { "C", { "3","4","5" } }, 
        { "D", { "4","5","6" } } 
    };
    const std::string label = "request: ";
    for (const auto& req : std::list<args_t> { {"5"}, {"4","3"}, {"1","3"} })
    {
        std::cout << boost::accumulate(req, label) << std::endl;
        for (auto& svc : services | filtered(applicable(req)))
            std::cout << "applicable: " << svc.first << std::endl;
    }
}

当然,可以应用许多优化。但你知道他们怎么说过早优化:)

输出:

request: 5
applicable: C
applicable: D
request: 43
applicable: B
applicable: C
request: 13
applicable: A